简体   繁体   English

使用道具反应选择处理 onChange

[英]react-select handle onChange with props

I am using react-select in a child component but wanting to store the Select value in a state in the parent.我在子组件中使用 react-select 但希望将 Select 值存储在父组件中的状态中。

I appreciate that I have to store onChange in state and then pass this to the Select value, but I would like to keep this temporary onChange state in the child component not the parent.我很感激我必须将 onChange 存储在 state 中,然后将其传递给 Select 值,但我想将这个临时 onChange 状态保留在子组件而不是父组件中。

So the question is how do I set the parent state (coming in on a prop) from the onChange state in the child.所以问题是我如何从孩子的 onChange 状态设置父状态(进入道具)。

Parent Component父组件

campaignName (campaign){
  //will setState here
   console.log(campaign)
  }
...
<FormGroup>
  <Campaign
    campaignName={this.campaignName.bind(this)}
    campaignOptions={code in here that sets option}
   />
</FormGroup>

Child Component子组件

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}
/>

Pass the function directly from parent to child that will handle the onChange:将函数直接从父级传递给将处理 onChange 的子级:

Parent Component父组件

handleSelect(e) {
   this.setState({
       selectValue: e.target.value,
   });
}

render() {
    <ChildComponent selectOnChange={this.handleSelect} />
}

Child Component子组件

<Select
   onChange={this.props.selectOnChange}
   value={this.props.campaignName}
/>

OR (if you want the method to stay on the child)或(如果您希望该方法留在孩子身上)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM