将数据从子组件传递到父组件 - 通过回调函数进行响应 [英] passing data from child to parent component - react - via callback function

查看:288
本文介绍了将数据从子组件传递到父组件 - 通过回调函数进行响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过回调函数
将数据从子组件传递到父组件但不知何故它不起作用。
我在这里做错了什么?
将数据从子组件传递到父组件 - 反应 - 通过回调函数

passing data from child to parent component via callback function but somehow it's not working. what am I doing wrong here? passing data from child to parent component - react - via callback function

https://codepen.io/silentarrowz/pen/GEMQEP?editors=0010

这里是代码

class App extends React.Component{
    constructor(props){
      super(props);
      this.state={
        input:'this is the input for now'
      }
   //this.handleInput=this.handleInput.bind(this);   
    }

    handleInput(x){
      this.setState({
        input:x
      });
      alert(this.state.input);
    }

  render(){
    return(
      <div>
        <h1>Passing props from Child to Parent Component</h1>
        <Child getInput={this.handleInput} />
        here's the input: {this.state.input}
        </div>
    );
  }
 }

class Child extends React.Component{
  constructor(){
    super();
    this.state={
      text:''
        }
    }
  passingProps(e){
    var newInput=e.target.value;
    //alert(newInput);
   this.setState({
     text:newInput
    });
  this.props.getInput(this.state.text);
  }

  render(){
    return(
      <div>
      <input type="text" placeholder="please input a name..." onChange={this.passingProps} />

        </div>

    )
  }
}

ReactDOM.render(
  <App/>,
  document.getElementById('app')
);


推荐答案

有几个问题。

1)你必须绑定 passingProps

constructor(){
    super();
    this.state={
      text:''
    }
    this.passingProps = this.passingProps.bind(this);
}

2) this.setState 是异步的,因此无法保证将 this.state.text 设置为您将其传递给时的所需值.props.getInput 。你可以这样做

2) this.setState is asynchronous, so it's not guaranteed that this.state.text will be set to the value you want by the time you pass it to this.props.getInput. You can either do

this.props.getInput(newInput)

this.setState({ text: newInput }, () => {
  this.props.getInput(this.state.text);
})

解决该问题。

这篇关于将数据从子组件传递到父组件 - 通过回调函数进行响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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