我的目标是使用来自端点的数据创建反应选择选择,该端点具有类别的查询变量(在此示例中为风味)。因此,我想动态创建这些选择输入,并设置了一个组件来包装主要的反应选择代码,因此我只需要一个处理函数。
这是我的主文件
const flavours1 = [
{ value: "chocolate", label: "Chocolate" },
{ value: "strawberry", label: "Strawberry" }
];
const flavours2 = [
{ value: "banana", label: "Banana" },
{ value: "kiwi", label: "Kiwi" }
];
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
test: "test",
selectedOptions: null
};
}
// Here I want to setState but with the name of each SelectComponent as the key for each object and also push to the existing array rather than over writing it as is currently
addSelectedOption = (...args) => {
this.setState({
selectedOptions: [args[0]]
});
};
componentDidUpdate() {
console.log(this.state);
}
render() {
return (
<div style={styles}>
<SelectComponent
name="flavours1"
options={flavours1}
addSelectedOption={this.addSelectedOption}
/>
<SelectComponent
name="flavours2"
options={flavours2}
addSelectedOption={this.addSelectedOption}
/>
</div>
);
}
}
以及组件:
import Select from "react-select";
export default class SelectComponent extends Component {
constructor(props) {
super(props);
this.state = {
selectedOptions: null
};
}
render() {
return (
<form>
<Select
isMulti
onChange={this.props.addSelectedOption}
value={this && this.state ? this.state.option : null}
options={this.props.options}
ref={input => {
this.selectField = input;
}}
/>
</form>
);
}
}
到目前为止,这是我的示例:https://codesandbox.io/s/llzw409n3z
所以我正在努力的两件事是:
目标是获得结构
selectedOptions: [
flavours1: [
{ value: "chocolate", label: "Chocolate" },
{ value: "strawberry", label: "Strawberry" }
],
flavours2: [
{ value: "banana", label: "Banana" },
{ value: "kiwi", label: "Kiwi" }
],
];
答案 0 :(得分:1)
当前react-select
组件未提供触发change
事件的组件的名称。因此,您需要通过使SelectComponent
在内部处理onChange
事件,然后将this.props.name
传递给addSelectedOption
处理程序来添加它。
添加
handleChange = (...args) => {
this.props.addSelectedOption(this.props.name, ...args)
}
并应用
<Select
onChange={this.handleChange}
...
/>
现在您可以在添加组件上使用
addSelectedOption = (name, options) => {
this.setState(({selectedOptions})=>({
selectedOptions: {
...selectedOptions,
[name]: options
}
}))
};
但是您必须像这样初始化state
this.state = {
test: "test",
selectedOptions: {}
};
以便您在使用selectedOptions
时可以传播setState
。