[英]React using react-select with multiple <Select /> tags
I'm trying to make multiple selection-inputs using React and react-select. 我正在尝试使用React和react-select进行多个选择输入。
How can I manage elements with multiple states? 如何管理具有多个状态的元素?
I make elements using loop (map) and after that how can I determine what value is going to be the next value for value prop? 我使用循环(映射)制作元素,然后如何确定值道具的下一个值将是哪个值?
How can I somehow save values that I got from onChange callback as states, and then assign it to proper element? 如何以某种方式将从onChange回调获取的值保存为状态,然后将其分配给适当的元素?
Now whenever I change my input (onChange calls handleChange), it's saving current selected value (as expected) but when I change input in another element, the previous element value goes back to "", and I'm only changing values in the current one. 现在,无论何时更改输入(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
/>
I believe this is what you are looking for 我相信这就是您要寻找的
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')
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.