在react-select中选择选项时,输入值不会改变

时间:2017-03-09 08:39:52

标签: javascript reactjs react-select

我正在使用react-select在我的react应用程序中定义一个select输入控件。这就是我使用该组件的方式:

<Select
   onChange={function(e) {console.log(e)}}
   options={[
      {value: "sf", label: "San Francisco"},
      {value: "nyc", label: "New York City"}
   ]}
></Select>

在选择任何选项之前,我会看到Select...占位符作为输入值。选择一个选项后,这不会改变:输入值不会改变,Select...占位符似乎是所选的“选项”。

我是如何使用该组件的?

1 个答案:

答案 0 :(得分:3)

Select变量中定义state值,logChange函数将返回object,将value的{​​{1}}分配给object状态变量,它将工作,检查此代码:

&#13;
&#13;
class App extends React.Component{

  constructor(){
     super();
     this.state = {value: ''}
  }
   
  logChange(val) {
    console.log("Selected: " + val.value);
    this.setState({value: val.value});
  }

  render(){
    var options = [
       {value: 'one', label: 'One' },
       {value: 'two', label: 'Two' } 
    ];
    return(
      
      <Select
          name="form-field-name"
          value={this.state.value}
          options={options}
          onChange={this.logChange.bind(this)}
      />
      
    )
  }
}

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>
<script src="https://unpkg.com/classnames/index.js"></script>
<script src="https://unpkg.com/react-input-autosize/dist/react-input-autosize.js"></script>
<script src="https://unpkg.com/react-select/dist/react-select.js"></script>

<link rel="stylesheet" href="https://unpkg.com/react-select/dist/react-select.css">

<div id='app'/>
&#13;
&#13;
&#13;