我在渲染中使用了開關複選框,因此檢測它是否爲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 –