使用带有多个<select>标签的react-select进行反应

时间:2018-02-07 14:45:31

标签: javascript node.js reactjs jsx

我尝试使用React和react-select进行多个选择输入。 如何管理具有多个状态的元素? 我使用循环(map)创建元素,然后我如何确定哪个值将成为值prop的下一个值? 我怎么能以某种方式将我从onChange回调中获得的值保存为状态,然后将其分配给正确的元素? 现在,每当我更改输入(onChange调用handleChange)时,它都会保存当前选定的值(如预期的那样)但是当我在另一个元素中更改输入时,前一个元素值会返回到&#34;&#34;,而且我只改变当前值的值。 handleChange(el){     this.setState({         值:埃尔     }) } let options = values.map(value =&gt; {                 返回{                         value:value.name,                         label:value.name,                         类别:el,                         categoryName:data [el] .name                     }             }) &LT;选择  命名= {}埃尔  的className =&#39;选择滤波器&#39;  closeOnSelect = {FALSE}  的onChange = {this.handleChange}  noResultsText =&#39;无法找到过滤器&#39;  placeholder = {`搜索$ {nameNotCapitalized}`}  选项= {}选择  定界符=&#39 ;;&#39;  simpleValue  值= {}值  多 /&GT;

1 个答案:

答案 0 :(得分:1)

我相信这就是你要找的东西

class App extends React.Component {
  constructor (props) {
    super(props);
    // I am storing the inputs definition here, but
    // it could be something that you retrieve from
    // your redux store or an API call
    this.state = {
      inputs : [{
        name : 'vowels',
        value : 'a',
        options : ['a','b','c']
      }, {
        name : 'numbers',
        value : 1,
        options : [1,2,3]
      }]
    }
  }
  // createSelect creates the select input based
  // on the input definition in the state
  createSelect (inputOptions) {
    const {options} = inputOptions;
    // Create options for the select
    const opts = options.map((o) => {
      return (<option value={o}>{o}</option>)
    });
    // Choosing the value
    // if the state does not have a key with the name
    // of the select yet, then use the value of the input definition
    // when the select change its value this.state[inputOptions.name]
    // will be used
    const val = this.state[inputOptions.name] || inputOptions.value
    return (
      <select value={val} onChange={this.createChangeHandler(inputOptions.name)}>
        {opts}
      </select>
    )
  }
  // createChangeHandler is a curried function that
  // allows to specify which state value will be set
  createChangeHandler (field) {
    return (e) => {
      this.setState({
        [field] : e.target.value
      })
    }
  }

  renderSelects () {
    const {inputs} = this.state;
    return inputs.map((input) => {
      return this.createSelect(input)
    });
  }

  render () {
    return (
      <form>
        {this.renderSelects()}
      </form>
    );
  }
}


ReactDOM.render(
  <App/>, 
  document.querySelector('#root')
)

并且有一个demo