如何将事件传递给setState回调函数? [英] How can I pass event to setState callback function?

查看:104
本文介绍了如何将事件传递给setState回调函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

React是否可以将外部事件传递给setState的回调函数?

Is it possible in React to pass an external event to the callback function of setState?

示例

someFunc(event) { 
    this.setState(
        {
            value: event.target.value
        },
        () => {                 
            this.props.onChange(event);    // <- cannot pass to here                
        }
    );
}

编辑:请参阅Liam的下面接受的解决方案,以获得优秀的答案,
以下是我的问题的具体解决方案:

See accepted solution below by Liam for an excellent answer, Here is the specific solution to my problem:

解决方案

someFunc(event) { 
    event.persist() // <- add this line and event should pass without a problem
    this.setState(
        {
            value: event.target.value
        },
        () => {                 
            this.props.onChange(event);                 
        }
    );
}


推荐答案

您需要提取值或使用 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>

或者如果您打算通过值状态你可以在回调中使用this.state.value它将起作用。

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                
        }
    );
}

这篇关于如何将事件传递给setState回调函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆