我有一个React Component
,其中Form
有多个Select
。
这些options
组件中的Select
作为SearchComponent
传递给props
。
我想将所选选项存储在本地state
中,一旦按下表单的Submit
,它就会被发送到将{_ 1}}函数传递给的父组件 - prop
。
由于select是多个,我有一个包含所有选项的数组,可以选择并存储在状态中。
searchStatements
class SearchComponent extends Component {
state = {
companies: [],
years: [],
currencies: []
};
render() {
return (
<Form
onSubmit={(e) => {
this.props.searchStatements(this.state.years,
this.state.currencies,this.state.companies);
}}
>
<Select
multiple=true
value={this.state.companies}
options={this.props.companies}
onChange={(e) => this.handleSelectChange('companies', e)}
/>
<Select
multiple=true
value={this.state.years}
options={this.props.years}
onChange={(e) => this.handleSelectChange('years', e)}
/>
<Select
multiple=true
value={this.state.currencies}
options={this.props.currencies}
onChange={(e) => this.handleSelectChange('currencies', e)}
/>
</Form>
);
}
handleSelectChange = (name, v) => {
if (name === 'currencies') {
const newArray = this.state.currencies;
newArray.push(v);
this.setState({'currencies': newArray});
} else if (name === 'companies') {
const newArray = this.state.companies;
newArray.push(v);
this.setState({'currencies': newArray});
} else if (name === 'years') {
const newArray = this.state.years;
newArray.push(v);
this.setState({'years': newArray});
}
};
}
就像这样 -
initial state
添加货币state = {
companies: [],
years: [],
currencies: []
};
时,它应该变为
USD
同样,当添加货币state = {
companies: [],
years: [],
currencies: ['USD']
};
时,它应该变为
GBP
然而,在state = {
companies: [],
years: [],
currencies: ['USD', 'GBP']
};
中,在添加了几个选项后,它就变成了这样的东西 -
handleSelectChange()
如何更改state = {
companies: [['GOOGLE'], ['GOOGLE', 'FACEBOOK']],
years: [],
currencies: [['USD'], ['USD', 'GBP']]
};
以使我的最终输出看起来像这样 -
handleSelectChange()
答案 0 :(得分:3)
因为您在Select
中使用了多个值,例如this.state.years
是您选择的所有年份的数组。因此,您应该分配所选的值(不是推/附加)。所以handleSelectChange
方法应该是
handleSelectChange = (name, v) => {
this.setState({[name]: v});
};