我尝试将组件渲染Counter
给其componentDidMount上的另一个组件Panel
。我还将名为count
的状态作为道具传递给Counter
。在某个时间间隔内,我会更新状态。但问题是Counter
的道具没有更新。道具仍然是初始值。是什么原因?
/** @jsx React.DOM */
var Panel = React.createClass({
getInitialState: function(){
return {
count: 0
}
},
tick: function() {
setInterval(function(that) {
that.setState({
count: that.state.count + 1
});
}, 500, this);
},
componentDidMount: function() {
var panel = React.findDOMNode(this.refs.panel);
React.render(<Counter count={this.state.count}/>, panel);
this.tick();
},
render: function(){
return <div ref="panel"></div>;
}
});
var Counter = React.createClass({
render: function() {
return <p>{this.props.count}</p>
}
});
React.render(<Panel/>, document.getElementById('container'));
<body>
<div id="container"></div>
</body>
我想知道此代码无效的原因
JS Bin check here
答案 0 :(得分:1)
这段代码是香蕉。为什么要在组件内调用React.render
?只需在render
函数中渲染计数器。
/** @jsx React.DOM */
var Panel = React.createClass({
getInitialState: function(){
return {
count: 0
}
},
tick: function() {
setInterval(function(that) {
that.setState({
count: that.state.count + 1
});
}, 500, this);
},
componentDidMount() {
this.tick();
},
render: function(){
return <div ref="panel"><Counter count={this.state.count}/></div>;
}
});
var Counter = React.createClass({
render: function() {
return <p>{this.props.count}</p>
}
});
React.render(<Panel/>, document.getElementById('container'));