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