【发布时间】:2016-10-02 16:20:34
【问题描述】:
我有一个按钮,当它被按下时,它将更新其父级的状态,这反过来又会更改父级的子元素的文本。
我有一个作为父类的 SiteContainer 类和一个作为子类的 NavBar 类。 NavBar 类包含两个元素,一个是按钮,另一个是标签。我希望这样当我按下按钮时,它会调用父元素中的一个函数,该函数将更新其状态,然后更新子元素的状态
我的问题是,当我在单击按钮后更新父状态时,新状态不会传递给子级进行重新渲染。
这是我的 SiteContainer 类:
var SiteContainer = React.createClass({
getRandomCustomerID: function() {
console.log("getting random id");
//just setting a test state for now, to fetch from server later
this.setState({id: "test"});
},
getInitialState: function() {
return {id: "customer_id"};
},
render: function() {
return (
<div>
<NavBar id={this.state.id} getRandomCustomerID={this.getRandomCustomerID}/>
</div>
);
}
})
这是我的导航栏类:
var NavBar = React.createClass({
componentDidMount: function() {
this.setState({id: this.props.id});
},
onClick: function() {
console.log("next button pressed");
this.props.getRandomCustomerID();
},
getInitialState: function() {
return {id: this.props.id};
},
render: function() {
return (
<div className="row">
<div className="col-md-6">
<h3>Customer ID: {this.state.id}</h3>
</div>
<div className="col-md-6">
<button className="btn btn-primary" onClick={this.onClick}>Next</button>
</div>
</div>
);
}
})
我做错了什么?
【问题讨论】:
-
请看一下这个问题表格更多的澄清stackoverflow.com/questions/25336124/…
标签: reactjs