简体   繁体   中英

Update state and call parent onChange handler simultaneously from child component during onChange event

I am trying to do two things when the child component's select element is changed-

  1. update child state (used to display more fields and in other child-specific decisions etc.),
  2. call parent handler passed in props.

Only 1st one is working, how do I add 2nd one also? Whats the proper way?

Dummy code:

class Child {
    render(){
        return(
            <div>
            //....
            <select 
                id={this.state.searchId}
                value={this.state.searchId}
                onChange={
                    //1. event => this.setState({searchId : event.target.value})
                    //2. call parent props changeHandler
                }>
                {options}
            </select>
            //....
            </div>
        )
    }
}

class Parent {
    onSearchPrefChange(e) {
        this.setState({
            searchId : e.target.value
        })
    }

    render(){
        <Child onChange={this.onSearchPrefChange} />
    }
}

I tried:

onChange={e => {
    this.setState({searchId : e.target.value});
    this.props.onSearchPrefChange;
}}>

The parent handler is not called, which also is used to change state of parent with same changed element's value/id.

You can define onChange event handler in the child component, set child's set there and call the callback passed from the parent in props from the function. Here is example code:

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.onSelectChange = this.onSelectChange.bind(this);
  }
  onSelectChange(e) {
    const newValue = e.target.value;
    this.props.onChange(newValue );
    // set child state here
    this.setState({searchId : newValue })
  }
  render() {
    return (
      <div>
        <select onChange={this.onSelectChange}>
          <option value="1">1</option>
          <option value="2">2</option>
        </select>
      </div>
    )
  }
}

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.someHandler = this.someHandler.bind(this);
  }
  someHandler(childValue) {
    console.log(childValue);
    this.setState({ value: childValue })
  }
  render() {
    return <Child onChange={this.someHandler} />
  }
}

Here is a working example on codesandbox .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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