2017-06-18 5 views
0

同じ質問が複数あることに同意します。私は数時間にわたり多くの研究をしましたが、この簡単に見えるエラーを解決することはできませんでした。 How to pass props to {this.props.children}投稿によると、私はReact.cloneElementReact.Childrenの使いやすいことを理解しています。私の子コンポーネントに続きネストされたルートを使用してthis.props.childrenに状態を渡す

class AboutPage extends React.Component { 

constructor(props, context){ 
    super(props, context); 

    this.state = { 
     details: "details" 
    } 
} 
render() { 

    const childrenWithProps = React.Children.map(this.props.children, 
     (child) => { 
      React.cloneElement(child, { 
       details: this.state.details 
      }) 
     } 
    ); 

    return (
     <div className="jumbotron"> 
      <h1>About</h1> 
      <p>This application uses React, Redux, React Router and other libs for our EducationOne Project</p> 
      <Link to="/about/Owner"> 
       <Button color="primary">test</Button> 
      </Link> 
      {childrenWithProps} 
     </div> 

    ); 
    } 
} 

AboutPage.PropTypes = { 
    children: PropTypes.object.isRequired 
}; 

されています:以下の

は私の親クラスである

const Owner = (props) => { 
return (
    <div>Owner details: {props.details}</div> 
); 
}; 

代わりの子や親をインポートし、私が作成するための私のroutes.jsにルートを入れ子になりましたaboutPageの子:

export default (
<Route path="/" component={App}> 
    <IndexRoute component={Login} /> 
    <Route path="home" component={HomePage}/> 
    <Route path="about" component={AboutPage}> 
     <Route path="omkar" components={Omkar} /> 
    </Route> 
    <Route path="courses" component={CoursesPage}> 
     {/*<IndexRoute components={CourseDetailsAndList}/>*/} 
    </Route> 
</Route> 
); 

は、しかし、私はすべてのエラーまたは内の任意のメッセージを参照してくださいいけませんコンソール、子コンポーネントをロードするためにボタンをクリックしたときに子コンポーネントがロードされることはありません。

本当にありがとうございます。

答えて

3

問題はmapの機能にあります。かっこ付きのコールバック矢印function has block bodyです。したがって、returnキーワードでクローンされた要素を明示的に返す必要があります。

簡潔なボディでは、式だけが必要であり、暗黙的な リターンが添付されています。ブロック本体では、明示的な戻り値 ステートメントを使用する必要があります。

const childrenWithProps = React.Children.map(this.props.children, child => { 
    return React.cloneElement(child, { 
    details: this.state.details 
    }); 
}); 
+0

おかげでたくさん... – Omkar

+0

おかげでたくさん...それは非常に有用だった...私はそれがどのように機能するか見てみましょう。 – Omkar

関連する問題