简体   繁体   English

反应:将状态从孩子传递给孩子到父母

[英]React: Passing state from child to child to parent

I am trying to pass a value through 2 child elements to the parent. 我试图通过2个子元素将值传递给父元素。 The chain looks like this: 链看起来像这样:

Child1 > Child2 > Parent

However, My parent handler is not grabbing the value in Child1 . 然而,我的父母处理程序不敛于值Child1 I trying to console log the state of theString in the parent component, however, nothing displays. 我试图控制在父组件中记录theString的状态,但是,没有显示任何内容。 How do i pass the handler function to child1 and grab its value to store in state? 我如何将处理函数传递给child1并获取其值以存储在状态?

Child 1 孩子1

  <input ref="theString" type="string" onChange={this.props.handleChangeOfString} value={this.state.theString} />

Child 2 Component 儿童2组件

<Tab tabId="4">
   {this.props.nav4Content}
   {this.props.handleChangeOfString}
</Tab>

Parent Constructor: 构造函数:

constructor(props) {
    super(props);
    this.state = {
       theString: ''
    };
    this.handleChangeOfString = this.handleChangeOfString.bind(this);
}

Parent Component: 组件:

<StringComponent
  nav4Content={colorsTab}
  onChange={this.handleChangeOfString}
/>

Parent Handler: 处理程序:

handleChangeOfString(e) {
  this.setState({theString: e.target.value})
}

The issue is how you are passing props from child2 to child1 . 问题是你如何将道具从child2传递给child1 You are not passing the values as props but as children in the child2 component. 您没有将值作为props传递,而是作为child2组件中的children传递。 Change it to 将其更改为

<Tab 
   tabId="4" 
   nav4Content={this.props.nav4Content} 
   handleChangeOfString={this.props.onChange}
/>  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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