gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 17:55:12 25 4
gpt4 key购买 nike

我同意有多个相同的问题被问到。我花了几个小时做了很多研究,但是我无法解决这个看起来很简单的错误。根据How to pass props to {this.props.children}发布后,我了解了 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>
);

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

任何帮助将不胜感激。

最佳答案

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

In a concise body, only an expression is needed, and an implicit return is attached. In a block body, you must use an explicit return statement.

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

关于javascript - 使用嵌套路由将状态传递给 this.props.children,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44611246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com