2017-01-17 20 views
0

以下のようなコンポーネント構造を持つ1つのアプリケーションがあります。 {this.props.children}を使用して、すべてのコンポーネントのヘッダをロードコンポーネントアプリメイン親 コンポーネントヘッダー コンポーネントホーム コンポーネントダッシュボード コンポーネントデータ コンポーネントDATALOADreact.js多段コンポーネント内に小道具と状態を入れよう

アプリケーションはヘッダに含まれているが、いくつかの状態変数を渡すレンダリング。 ホームには、ヘッダーを更新するためにAppの状態変数を更新するアクションを持つDashboardが含まれています。 データにはここからもDataLoadが含まれています。ヘッダーを更新するには、Appの状態変数を更新する必要があります。

For example my App is like 
import React from 'react'; 
import Header from './Header.jsx'; 
class App extends React.Component { 
constructor(props) { 
    super(); 
    this.state = { 
       show : '1', 
      } 
    this.showHide = this.showHide.bind(this); 
} 

showHideSearch() { 
    this.setState(prevState => ({ 
     show: prevState.show == '1' ? '0' : '1', 
    })); 
} 
render() { 
return (
    <div> 
     <Header show={this.state.show}/> 
     {this.props.children} 
    </div> 
) 
} 
} 

export default App; 

import React from 'react'; 
import Dashboard from './Dashboard.jsx' 
class Home extends React.Component { 
constructor(props) { 
    super(); 
    this.showHide = this.showHide.bind(this); 
} 
showHide() { 
     tried this but not working 
    //this.props.showHideSearch(); 
} 
render() { 
return (
    <div>// this props show not going to dashboard component 
     <Dashboard show={this.props.show} showHide= {this.showHide.bind(this)}/> 
    </div> 
) 
} 
} 

export default Home; 
+0

これをチェックしてください(http://stackoverflow.com/questions/32370994/how-to-pass-props-to-this -props-children)。 –

+0

[{this.props.children}に小道具を渡す方法]の複製があります(http://stackoverflow.com/questions/32370994/how-to-pass-props-to-this-props-children) –

答えて

0

私は右のあなたの質問を理解していた場合、あなたはthis.props.childrenでそのコンポーネントにアプリのコンポーネントからごthis.showHideSearch関数を渡すために欠けている - あなたのホームコンポーネント。

これは、使用して簡単に達成可能である:

React.cloneElement(this.props.children, {showHideSearch: this.showHideSearch});

あなたはthis.props.childrenを持っている場所の代わりにそれを入れてください。

ソース - https://stackoverflow.com/a/35102287/6621973


編集:単に親から子へと状態を設定する機能を伝承、親の状態を更新します。たとえば、Googleが「親の状態を変えて反応する」場合、いくつかの例があります。How to update parent's state in React?

+0

私はどのように私は1つの状態変数を更新する方法を参照しようとしていた主なアプリケーションコンポーネントで使用されている別のコンポーネントを別のコンポーネントを –

+0

親の状態を更新するには、単純に親から子に状態を設定する関数を渡します。あなたがGoogleの "変化の親の状態に反応する"場合、いくつかの例があります:http://stackoverflow.com/questions/35537229/how-to-update-parents-state-in-react –

関連する問題