反应选择映射问题 [英] React Select mapping issue
问题描述
我在我的项目中使用了 react-select 并且我正在使用它像这样的 map
:
I'm using react-select in my project and I'm using it within a map
like that:
renderItems() {
this.props.items.map(item => (
<Select
id="options"
value={this.state.optionSelected}
onChange={this.onChangeOption}
options={this.showOptions()}
/>
);
}
它正确显示了我所有项目的所有选项,但现在我无法摆脱选择...
It show correctly all my options for all my items but now I can not get rid about the select...
基本上,当我在单个项目上选择一个选项时,该选项会针对所有项目更改...
Basically when I select an option on a single item, that option is changing for all items...
这是我目前所做的:
onChangeOption(e) {
this.setState({ optionSelected: e.value });
}
如何调整它以仅在我希望更改的选项上更改选项?
How can I adjust it to change the option only on the one I wish to change it?
谢谢
推荐答案
您对所有选择组件使用相同的更改处理程序,然后为所有选择组件设置相同的状态值.为了解决这个问题,您要么需要将选择组件与处理其自身状态和更改事件的容器组件分开,要么您需要为每个选择组件提供一个唯一的状态值.
You are using the same change handler for all of your select components and then set the same state value for all your select components. To deal with this either you need to separate your select components with a container component that handles their own state and change event or you need to give each select component a unique state value.
示例
renderItems() {
this.props.items.map(item => (
<Select
id="options"
value={this.state.optionSelected[item.id]}
onChange={(event) => this.onChangeOption(event, item.id)}
options={this.showOptions()}
/>
);
}
onChangeOption(event, itemId) {
this.setState((prevState) => {
const prevStateClone = Object.assign({}, prevState);
prevStateClone.optionSelected[itemId] = event.target.value;
return prevStateClone;
});
}
这篇关于反应选择映射问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!