2017-06-18 50 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