How can I pass event to setState callback function?

早过忘川 提交于 2019-12-04 14:11:06

You need to extract the values or use e.persist()

https://reactjs.org/docs/events.html#event-pooling

class App extends React.Component {

something = (value) =>{
  {console.log(value, 'coming from child')}
}
  render() {

    return (
      <div >
        <Hello text={this.something} />
      </div>
    );
  }
}


class Hello extends React.Component {

  constructor() {
    super()
    this.state = {
      value: ''
    }
  }
  onChange = (e) => {
    const value = e.target.value;
    this.setState({ value }, () => {
    
      this.props.text(value)
    })
  }
  render() {

    return (
      <div style={{ padding: 24 }}>
        <input onChange={this.onChange} value={this.state.value} />

      </div>
    );
  }
}



ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='root' ></div>

Or if you meant to pass the value state you can use this.state.value in callback it will work.

someFunc(event) { 
    this.setState(
        {
            value: event.target.value
        },
        () => {                 
            this.props.onChange(this.state.value);    // <- this should work                
        }
    );
}

EDIT: WRONG SOLUTION

One solution is to write another function an reference that e.g.

updateInput(e) {
    this.setState(
        {
            value: e.target.value
        },
        this.handleUpdate(e)
    );
 }

handleUpdate(e) {
    this.props.onChange(e, this.props.tag);
}

EDIT:

As pointed out in the comments below by Felix King, this is not a solution at all. It will run the handleUpdate function before the state has been set which defeats the purpose. The real solution is posted above by Liam.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!