使用嵌套路由将状态传递给this.props.children

时间:2017-06-18 02:40:05

标签: javascript reactjs react-router

我同意有同样的问题。我做了很多研究了几个小时,然而,我无法解决这个容易看错的错误。根据{{​​3}}帖子,我了解React.cloneElementReact.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>
);

但是,当我点击按钮加载子组件时,我在控制台中看不到任何错误或任何消息,也没有加载子组件。

任何帮助都将非常感激。

1 个答案:

答案 0 :(得分:3)

问题出在您的map功能中。带有括号的回调箭头function has block body,因此您需要使用return关键字显式返回克隆元素。

  

在一个简洁的正文中,只需要一个表达式,一个隐含的表达式   返回附上。在块体中,您必须使用显式返回   言。

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