【问题标题】:How to get an input value using "refs" in react-bootstrap form?如何使用 react-bootstrap 表单中的“refs”获取输入值?
【发布时间】:2017-04-26 09:30:30
【问题描述】:

我正在尝试创建一个以模式显示的表单。因此,当用户输入一个值时,该值将存储在本地存储中。这张图片可以帮助你理解我的意思:
这是表单的代码:

function FieldGroup({id, label, help, ...props}) {
    return (
        <ReactBootstrap.FormGroup controlId={id}>
            <ReactBootstrap.ControlLabel>{label}</ReactBootstrap.ControlLabel>
            <ReactBootstrap.FormControl {...props} />
            {help && <ReactBootstrap.HelpBlock>{help}</ReactBootstrap.HelpBlock>}
        </ReactBootstrap.FormGroup>
    );
}

const formInstance = (
    <form>
        <FieldGroup
            id="formControlsText"
            type="text"
            label="Text"
            placeholder="Recipe Name"
            inputRef={ref => { this.input = ref; }}
        />
        <ReactBootstrap.FormGroup controlId="formControlsTextarea">
            <ReactBootstrap.ControlLabel>Ingredients</ReactBootstrap.ControlLabel>
            <ReactBootstrap.FormControl componentClass="textarea" placeholder="Enter Ingredients" />
        </ReactBootstrap.FormGroup>
    </form>
);  

正如我在引导 React 教程中所读到的,我应该将
&lt;FormControl inputRef={ref =&gt; { this.input = ref; }} /&gt; 添加到 FormControl 道具中。但是在添加它之后,当调用模态表单时出现错误:

`

【问题讨论】:

    标签: reactjs react-bootstrap


    【解决方案1】:

    我刚刚提出了这个问题。我的代码:

    <FormControl
        componentClass="input"
        placeholder="Enter recipe title"
        inputRef={(ref) => {this.input = ref}}
        defaultValue={title}/>
    </FormGroup>
    

    然后你可以在这样的处理程序中从&lt;FormControl&gt; 获取值:

    console.log(this.input.value);
    

    详细信息可以在我的仓库中找到:https://github.com/kerf007/recipebook

    【讨论】:

      【解决方案2】:

      我和你有同样的问题,这是我的解决方案

      const FieldGroup = ({id, label, help, inputRef, ...props}) =>
        <FormGroup controlId={id}>
          <ControlLabel>{label}</ControlLabel>
          <FormControl {...props} inputRef={inputRef}/>
          {help && <HelpBlock>{help}</HelpBlock>}
        </FormGroup>
      

      还有我的表格

      <form>
          <FieldGroup
              id="bookName"
              type="text"
              label="Name"
              placeholder="Enter name..."
              inputRef = {(input) => this.inputName = input }
           />
          <FieldGroup
              id="bookAuthor"
              label="Author"
              type="text"
              placeholder="author 's name..."
              inputRef={(input) => this.inputAuthor = input}
           />
      </form>
      

      然后您可以通过以下方式获取 book 的 name 和 author 的 name 值:

      this.inputName.value and this.inputAuthor.value
      

      【讨论】:

        【解决方案3】:

        这个问题(或者更像是工作方式的改变)与 React-Bootstrap 有关。你这样做的方式将不再有效。

        &lt;FormControl&gt; 组件直接渲染或其他指定的组件。如果您需要访问不受控制的&lt;FormControl&gt; 的值,像使用不受控制的输入一样将引用附加到它,然后调用ReactDOM.findDOMNode(ref) 以获取 DOM 节点。然后,您可以像处理任何其他不受控制的输入一样与该节点进行交互。

        这是一个例子:

        var React = require('react');
        var ReactDOM = require('react-dom');
        var FormControl = require('react-bootstrap').FormControl;
        
        React.createClass({
          render: function() {
            return (<FormControl ref="formControl" />);
          },
          getFormControlNode: function() {
            // Get the underlying <input> DOM element
            return ReactDOM.findDOMNode(this.refs.formControl);
          }
        });
        

        一旦您获得 DOM 元素,您就可以检索该值:this.getFormControlNode().value 或做任何您想做的事情。

        PS:这是一个关于这个主题的related github issue

        【讨论】:

          【解决方案4】:

          这对我有用,使用 https://reactjs.org/docs/refs-and-the-dom.html

           constructor(props) {
                  super(props);
                  this.email = React.createRef();
              }
          
          submit() {
                  var email = this.email.current.value;
                  console.log(email);
          }
          render() {
             return (
                      <Form>
                      <Form.Control type="email" placeholder="Your email" ref={this.email} />
                      <Button variant="primary" onClick={()=>this.submit()}>Send</Button>
                      </Form>
                     );
          }
          

          【讨论】:

          • 我怎样才能直接在状态变量上取这个值?@steven
          【解决方案5】:

          我认为它建议使用的是 ref 回调属性,所以只需将 inputRef 更改为 ref

          仅供参考:https://facebook.github.io/react/docs/refs-and-the-dom.html

          【讨论】:

          • 它没有改变任何东西,同样的错误。我认为问题在于 “您可能不会在功能组件上使用 ref 属性,因为它们没有实例。”
          • 您可以在功能性无状态组件上使用ref属性:robinwieruch.de/react-ref-attribute-dom-node
          【解决方案6】:

          您好,这个解决方案对我有用!

          <Form
            noValidate
            validated={validated}
            onSubmit={(e) => this.handleSubmit(e)}
            style={{ width: '100%' }}
          >
            <Form.Group controlId="formBasicEmail">
             <Form.Label>Email address</Form.Label>
             <Form.Control type="email" placeholder="Enter email" inputRef={(ref) => { this.email = ref }} required />
             <Form.Text className="text-muted"> Well never share your email with anyone else.
             </Form.Text>
            </Form.Group>
          </Form>
          
          handleSubmit(event) {
              console.log(event.target.elements.formBasicPassword.value)
          }
          

          【讨论】:

            【解决方案7】:

            我想我找到了如何从 React-Bootstrap &lt;Form/&gt; 获取 ref

             import React, {createRef} from 'react'  
            
                interface definedProps {} 
                interface definedState {
                              myRef: Object //I didn't found the more accurate type
                          } 
                export default class SomeClass extends React.Component<definedProps,definedState> {
                    state = {
                        myRef: React.createRef<Form<any>>() //That's it!
                    }
            
                const handleClose = () => {
                    console.log('this.state.myRef: ', this.state.myRef); //Here we can take data from Form
                    debugger; //todo: remove
                }
            
                    render() {
            
                        return (
                            <div>
                                 <Form ref={this.state.myRef}> { /*Here we're connecting the form's ref to State*/}
                                    <Form.Group controlId='formName'>
                                        <Form.Control
                                            type='text'
                                            placeholder='Enter Name'
                                        />
                                    </Form.Group>
                                      ...
                                    <Button
                                        variant='primary'
                                        onClick={handleClose}
                                        >
                                        Save Changes
                                    </Button>
                                    </Form>
                            </div>
                        )
                    }
                }
            

            【讨论】:

            • 如果你使用的是“标准”
              ,而不是 React-Bootstrap,那么状态下 myRef 的值应该像这样初始化: myRef: React.createRef()
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2017-02-21
            • 1970-01-01
            • 2017-12-24
            • 2020-08-25
            • 1970-01-01
            • 2021-08-01
            • 1970-01-01
            相关资源
            最近更新 更多