[英]react-select handle onChange with props
我在子組件中使用 react-select 但希望將 Select 值存儲在父組件中的狀態中。
我很感激我必須將 onChange 存儲在 state 中,然后將其傳遞給 Select 值,但我想將這個臨時 onChange 狀態保留在子組件而不是父組件中。
所以問題是我如何從孩子的 onChange 狀態設置父狀態(進入道具)。
父組件
campaignName (campaign){
//will setState here
console.log(campaign)
}
...
<FormGroup>
<Campaign
campaignName={this.campaignName.bind(this)}
campaignOptions={code in here that sets option}
/>
</FormGroup>
子組件
updateValue (newValue) {
this.setState({
selectValue: newValue,
// how do I set the parent state from this
});
<Select
onChange={this.updateValue}
value={this.props.campaignName}
options={this.props.campaignOptions}
/>
將函數直接從父級傳遞給將處理 onChange 的子級:
父組件
handleSelect(e) {
this.setState({
selectValue: e.target.value,
});
}
render() {
<ChildComponent selectOnChange={this.handleSelect} />
}
子組件
<Select
onChange={this.props.selectOnChange}
value={this.props.campaignName}
/>
或(如果您希望該方法留在孩子身上)
updateValue(e) {
this.props.selectOnChange(e); //call the passed props here
}
<Select
onChange={this.updateValue}
value={this.props.campaignName}
/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.