【发布时间】:2015-12-03 13:05:26
【问题描述】:
我正在尝试熟悉 react.js 中组件之间的继承是如何工作的,但遇到了一些麻烦。
要求 - 基本上,我想要实现的是当我单击按钮时我的复选框的值会发生变化。
复选框继承'checkedVal' 的值,该值在标题中设置为状态。
我可以在第一次加载复选框时获得正确的值,但当我单击按钮时无法更改它。任何想法将不胜感激?
var Heading = React.createClass({
propTypes: {
name: React.PropTypes.string,
age: React.PropTypes.number
},
getDefaultProps: function(){
return {
name: 'Keir',
age: 24,
}
},
getInitialState: function(){
return {
manU: false,
checkedVal: false
}
},
manUFan: function(){
this.setState(function(previousState, currentProps){
return {
manU: !previousState.manU,
checkedVal: !previousState.checkedVal
}
});
},
render: function(){
var msg;
if(this.state.manU){
msg = "I am a United fan."
} else {
msg = "I dream of being a united fan."
}
return (
<div>
<h1>Attempting React</h1>
<ul>
<li>{this.props.name}</li>
<li>{this.props.age}</li>
</ul>
<button onClick={this.manUFan}>Do You Support Man U?</button>
<CheckBox checkBoxVal={this.state.checkedVal}/>
<p>{msg}</p>
</div>
)
}
});
var CheckBox = React.createClass({
propTypes: {
checkBoxVal: React.PropTypes.bool
},
render: function(){
return (
<div>
<input type="checkbox" defaultChecked={this.props.checkBoxVal}/>
</div>
)
}
});
ReactDOM.render(<Heading />, document.getElementById('content'));
【问题讨论】:
标签: javascript inheritance reactjs