gpt4 book ai didi

reactjs - 将状态作为属性传递给子组件

转载 作者:行者123 更新时间:2023-12-03 13:51:43 24 4
gpt4 key购买 nike

我目前正在学习 React router v1.0,对于将状态作为属性传递给子组件感到困惑。

App.js

  getInitialState: function(){
return {
status: 'disconnected',
title: ''
},
...
,
render: function(){
return (
<div>
<Header title={this.state.title} status={this.state.status}/>
{React.cloneElement(this.props.children,{title:this.state.title,status:this.state.status})}
</div>
);

客户端.js

var routes = (
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={Audience} />
<Route path ="speaker" component={Speaker} />
</Route>
</Router>
);

Audience.js

render: function(){
return(
<div>
<h1>Audience</h1>
{this.props.title || "Welcome Audience"}
</div>
);
}

扬声器.js

render: function(){
return(
<div>
<h1>Speaker:</h1>
{this.props.status || "Welcome Speaker!"}
</div>
);
}

不要这样做:

{React.cloneElement(this.props.children,{title:this.state.title,status:this.state.status})}

使用 https://facebook.github.io/react/docs/jsx-spread.html 的 React.cloneElement 是否有类似的东西运算符:

<RouteHandler {...this.state}/>

TLDR; 基本上,我想将整个状态传递给我的路由组件,而不是单独定义它们。

任何帮助将不胜感激!

最佳答案

嗯,简单的答案是否定的。

<小时/>

正如您在 this comment 中看到的那样- 有一些方法可以实现这种行为(您正在做的方式就是其中之一),也许您已经看到了所有这些方法,但我不建议您使用其中任何一种,除非确实有必要。

您确实应该在以下线程中查看有关它的讨论:

https://github.com/reactjs/react-router/issues/1857

https://github.com/reactjs/react-router/issues/1531

@ryanflorence [Co-author of React-router]

You should think of your route components as entry points into the app that don't know or care about the parent, and the parent shouldn't know/care about the children.

通常处理这些情况的最佳方法是使用类似 redux 的内容。 - 应用程序的整个状态存储在对象树中,并且可以在路由组件之间轻松共享。

关于reactjs - 将状态作为属性传递给子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36672009/

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