2017-01-16 62 views
1

我創建了三個基本組件。React.js傳遞組件之間的數據流

A渲染組件B和C B就像包含選項卡的標題1,2,3 C是第一個有兩種形式的頁面,每次顯示一個。在顯示第一種形式時,我需要在B組件中顯示選項卡1。在顯示第二種形式時,我需要顯示B組件中的選項卡3。

我只想從C組件的數據傳遞到B組件的基礎上。

我把狀態放在C組件上,並嘗試使用相同的this.state.data或this.props.data,因爲B控制器中沒有值。

A.jsx

import React from 'react'; 
import B from './B.jsx'; 
import C from './C.jsx' 
class A extends React.Component { 
    constructor(props) { 
     super(); 
     this.state = { 
      show : '1', 
     } 
    } 
    render() { 
     return (
      <div>{this.props.show} 
       <B /> 
       <C/> 
      </div> 
     ) 
    } 
} 

export default A; 

B.jsx

import React from 'react'; 

class B extends React.Component { 
    constructor(props) { 
     super(props); 
     this.state = { 
      show : '1', 
     } 
    } 
    render() { 
     return (
      //html code here 
     ) 
    } 
} 

C.jsx

class C extends React.Component { 
    constructor(props) { 
     super(props); 
     this.state = { 
      show : '1', 
     } 
    } 
    render() { 
     return (
      //html code here 
     ) 
    } 
} 
+0

你可以顯示你的代碼,你試過? –

+0

@MayankShukla我添加了一些代碼來理解。 –

回答

1

我試圖創建同樣的場景你所描述的,檢查jsfiddle作爲例子。

jsfiddlehttps://jsfiddle.net/mj8rsawh/

請上這個,如果你想要的任何其他幫助註釋。

+0

你能否描述一次? –

+0

我的理解是在父組件中添加更新功能。 然後將初始值傳遞給具有綁定函數的組件 如何將兩個值傳遞給它?例如顯示和隱藏? 然後在chlid組件中使用bind函數來更新值並在三個組件中檢索它。 –

+0

我知道如何在父母的孩子的道具和陳述作品。謝謝 –

3

您需要將您的狀態添加到父組件這裏將是一個組件,然後通過一個函數來改變你的狀態,以B和C,以改變一個喜歡你的狀態下面

class A extends React.Component { 
    constructor(props) { 
     super(); 
     this.state = { 
      show : '1', 
     }; 
    } 
    changeShow(show){ 
     this.setState({show: show}); 
    } 
    render() { 
     return (
      <div>{this.props.show} 
       <B show={this.state.show}/> 
       <C handleChangeShow={this.changeShow.bind(this)} show={this.state.show}/> 
      </div> 
     ) 
    } 
} 

現在你有訪問顯示在你的子組件狀態,並可以從他們在C更改例如

class C extends React.Component { 
    handleChange({target}){ 
     this.props.handleChangeShow(target.value) 
    } 
    render() { 
     return (
      <select onChange={this.handleChange.bind(this)}> 
       <option value="0">hide</option> 
       <option value="1">show</option> 
      </select> 
     ) 
    } 
} 

現在,你有機會在B到顯示狀態

class B extends React.Component { 

    render() { 
     return (
      {this.props.show} 
     ) 
    } 
} 

這是不夠清楚你在你的例子中想做什麼,所以我試圖給一個例子如何在一般意義上的子組件之間傳遞狀態。我希望它足夠有用

+0

我知道如何在父母的孩子的道具和陳述作品。謝謝 –

+0

林間空地有幫助 –