2016-11-14 42 views
1

我发现,我从父母通过refs传递到子组件参数可以是未定义或一个真实的事件,而不是我在传递参数传递给孩子组件的功能。调用,并从父组件在reactjs

是什么实际将参数从父项传递给子组件的函数的正确方法?我正在使用refs,但似乎它并没有真正通过函数参数来传递任何东西。

我在这里展示的情况: https://codepen.io/adamchenwei/pen/gLMaPo/?editors=0010

基本上,如果你看到我写的console.log('child argument should be string');应该是实际传递的,而不是一个事件的参数就行了。

我不知道我做错了什么。

对于这种情况,我需要在父组件中评估事件,并决定如何运行子函数,并相应地传入特定的参数。

回答

0

只有两种方式访问​​子组件中的父项道具。通过道具父

  1. 值传递到子组件从子状态,并派遣行动
  2. 设定值从国家获取值 - :您可以在以下两种方式实现这一目标。
0

而不是使用ref时,我会用状态和道具:

parentDoThing(event) { 
    const lifeTerms = { 
     heaven: 'yeeeeey', 
     hell: 'nooooooo', 
    } 
    if(event) { 
     this.setState({ lifeTerms: heaven }); 
    } else { 
     this.setState({ lifeTerms: hell}); 
    } 
} 

render() {  
    return (
     <section className="parent-comp" 
     onClick={this.parentDoThings}> 
     <ChildComponent 
      lifeTerms={this.state.lifeTerms}/> 
     <h1> Whats in App {this.state.text}</h1> 
     </section> 
);} 

而在子组件:

render() {  
    return (
     <section className="child"> 
     <section>this life is {this.state.life} </section> 
     <button onClick={this.doChildThings.bind(this, this.props.lifeTerms)}> Button </button> 
     </section> 
    ); 
0

通过使用componentWillUpdate解决了我的问题结合起来使用母公司层面state作为props传递给孩子,以触发孩子内部的事件,因为我不希望子内的任何触发器触发父代提供的更改。