【问题标题】:React using react-select with multiple <Select /> tags使用带有多个 <Select /> 标签的 react-select 进行反应
【发布时间】:2018-07-17 21:46:42
【问题描述】:

我正在尝试使用 React 和 react-select 进行多个选择输入。

如何管理具有多种状态的元素?

我使用循环(地图)制作元素,然后我如何确定哪个值将成为 value prop 的下一个值?

如何以某种方式将我从 onChange 回调中获得的值保存为状态,然后将其分配给适当的元素?

现在,每当我更改输入(onChange 调用 handleChange)时,它都会保存当前选定的值(如预期的那样),但是当我在另一个元素中更改输入时,之前的元素值会返回到“”,而我只是在更改值在当前的。

handleChange(el) {
    this.setState({
        value:el
    })
}

let options = values.map(value => {
                return {
                        value: value.name,
                        label: value.name,
                        category: el,
                        categoryName: data[el].name
                    }
            })

<Select 
 name={el}
 className='Select-filters'
 closeOnSelect={false}
 onChange={this.handleChange}
 noResultsText='Filter couldn't be found'
 placeholder={`Search ${nameNotCapitalized}`}
 options={options}
 delimiter=';'
 simpleValue
 value={value}
 multi
/>

【问题讨论】:

  • 您选择的输入是否有相同的选项?
  • 不是,我是根据api数据生成的

标签: javascript node.js reactjs jsx


【解决方案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

【讨论】:

  • 我考虑过使用柯里化。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2019-02-05
  • 1970-01-01
  • 2018-08-19
  • 2019-11-29
  • 2019-04-03
  • 1970-01-01
  • 2023-03-03
相关资源
最近更新 更多