2016-11-14 45 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傳遞給孩子,以觸發孩子內部的事件,因爲我不希望子內的任何觸發器觸發父代提供的更改。