我正在尝试更新较大组件的子组件的状态或属性 <Navigation />
以反射(reflect)我的网站上显示的内容。
这就是大局,我以为这会很容易,但事实并非如此。这是我的代码:
// This is the parent component
var Navigation = React.createClass({
getInitialState: function(){
var endpoints = require("./data/naviEnd.js");
return {
endpoints: endpoints
}
},
renderEndpoints: function(key){
var endpointDetails = this.state.endpoints[key];
return(
<NavEndpt activeRoute={this.props.activeRoute} toggleState={this.toggleState} id={endpointDetails.id} key={endpointDetails.title} url={endpointDetails.url} title={endpointDetails.title}/>
)
},
render: function() {
return(
<div id="navigation">
{Object.keys(this.state.endpoints).map(this.renderEndpoints)}
</div>
)
}
});
// this is the child component that renders the div and links contained inside
var NavEndpt = React.createClass({
handleClick: function() {
},
render: function() {
return(
<div id={this.props.id}>
<Link className={this.props.active} onClick={this.handleClick} id={this.props.id + "-link"} to={this.props.url}>{this.props.title}</Link>
</div>
)
}
})
我一直在尝试一大堆方法来更新状态并使用 props 传递信息,但没有任何效果。我的<Navigation />
组件没有 this.props.children
我认为会的,因为有两个子组件 <NavEndpt />
。 React 文档不是很有帮助。接下来我可以尝试什么?
最佳答案
所以我想我首先要问为什么你认为导航应该有 this.props.children - 我知道它有两个 child ,但它没有将它们作为 Prop 传递。它正在创造它们。如果像这样调用它,它将收到一个children props:
<Navigation>
<div>This is a child!</div>
</Navigation>
那里的 div 将作为名为“children”的 prop 传入。
现在,如果您尝试更改导航的状态并让它将一些信息传递到 NavEndpt,您可以设置如下内容:
var Navigation = React.createClass({
getInitialState: function() {
var endpoints = require("./data/naviEnd.js");
return {
endpoints: endpoints
}
},
changeEndpoints: function() {
// Get new endpoints somehow
this.setState({endpoints: newEndpoints});
}
render: function() {
return(
<div id="navigation">
<NavEndpt endpoints={this.state.endpoints} />
</div>
)
}
});
这将导致 NavEndpt 接收新的 Prop ,这些 Prop 是导航状态下的当前端点,每当它们更新时(就像我在我的愚蠢函数中那样,它代表一些点击或 ajax 请求或任何得到的东西)新端点)。
关于javascript - 更改组件的状态以反射(reflect)所选页面的 ReactJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39357663/