我在渲染中使用了开关复选框,因此检测它是否为checked
的一个重要属性是defaultChecked
。我之前在componentWillReceiveProps
中设置了状态。我尝试先将状态作为属性,但在编译代码为babel.js
时出现错误Unexpected token
。在我尝试使用dangerouslySetInnerHTML
之后,它仍然没有工作(底部错误)。如何在ReactJs中将状态用作检查的属性?
首先尝试:
<input type="checkbox" name="onoffswitch" {this.state.required} />
App.jsx
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
required: ''
};
};
componentWillReceiveProps(nextProps){
//more code
this.setState({
required: 'defaultChecked'
});
};
render() {
return(
<div id="section">
<div className="bottom-question">
<div>
<div className="onoffswitch-add pull-left">
<input type="checkbox"
name="onoffswitch"
dangerouslySetInnerHTML={this.state.required} />
<label className="onoffswitch-label-add" htmlFor="switch-required">
<div className="onoffswitch-inner-add"></div>
<div className="onoffswitch-switch-add"></div>
</label>
</div>
</div>
</div>
</div>
)
}
}
错误:
The full text of the error you just encountered is:
input is a void element tag and must neither have `children`
nor use `dangerouslySetInnerHTML`. Check the render method of EditInput
检查这个曾经有关如何使用复选框以reactjs https://facebook.github.io/react/docs/forms.html –