如何使用react ref从html select元素中获取值?

时间:2017-04-17 15:25:15

标签: javascript html reactjs

我有一个表单,我使用的是html select元素。

  <select className="form-control" id="ntype" required >
      <option value = "">None</option>
      <option value = "1">1</option>
      <option value = "2">2</option>
      <option value = "3">3</option>
  </select>

我知道使用html input类型元素,我们可以附加ref,如下面的代码

ref = {(input) => { this.nHeading = input; }}

<input
    type        = "text"
    className   = "form-control"
    id          = "tInput"
    placeholder = "Sample input"
    ref         = {(input) => { this.sInput = input; }}
    required
/>

如何在提交表单时附加引用<Select>元素并从附加的option value中选择ref

我是否需要将ref附加到每个选项或select元素本身?

2 个答案:

答案 0 :(得分:3)

您可以将值存储在更改状态,然后再使用它,即使其成为受控组件

&#13;
&#13;
class App extends React.Component {
constructor() {
super();
    this.state = {selectValue: ''}
    }
    callThis = (e) => {
        this.setState({selectValue: e.target.value}, ()=> {console.log(this.state.selectValue)});
        
    }
    render() {
    
      return (
          <select onChange={this.callThis}className="form-control" id="ntype" required >
              <option value = "">None</option>
              <option value = "1">1</option>
              <option value = "2">2</option>
              <option value = "3">3</option>
          </select>
         
      )
    }
}
ReactDOM.render(<App/>, document.getElementById('app'));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
&#13;
&#13;
&#13;

或者您可以使用refs获取此值

&#13;
&#13;
class App extends React.Component {
constructor() {
super();
    this.state = {selectValue: ''}
    }
    callThis = (e) => {
        console.log(this.selectVal.value)
        
    }
    render() {
    
      return (
          <div><select ref={(input) => this.selectVal = input} className="form-control" id="ntype" required >
              <option value = "">None</option>
              <option value = "1">1</option>
              <option value = "2">2</option>
              <option value = "3">3</option>
          </select>
          <input type="button" value="click" onClick={this.callThis}/></div>
      )
    }
}
ReactDOM.render(<App/>, document.getElementById('app'));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我会为每个元素赋予一个值和onChange处理程序,用于像

这样的select元素
<select className="form-control"onChange={this.onChange.bind(this)}>
    <option value="">None</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

定义一个onChange处理程序,用于设置选择的状态

onChange(e){
    this.setState({value: e.target.value}, function(){

    // do other stuff

});

}