我在渲染中使用了一个开关复选框,因此检测它是checked
是否为defaultChecked
的一个重要属性是componentWillReceiveProps
。我之前在Unexpected token
中设置了状态。我首先尝试将状态作为属性,但是当我用babel.js
编译代码时,我收到错误dangerouslySetInnerHTML
。我尝试使用<input type="checkbox" name="onoffswitch" {this.state.required} />
但它仍然无效(底部错误)。
首先尝试:
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>
)
}
}
App.jsx
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
错误:
public static
答案 0 :(得分:2)
您想使用checked
属性将检查应用于javascript中的复选框输入
<input type="checkbox" name="onoffswitch" checked={this.state.required === 'defaultChecked'} />
当你将required的状态设置为你想要的状态时(在这种情况下你使用的是字符串'defaultChecked'
),你需要告诉输入根据它来检查自己。
我建议你将状态变量重构成一个布尔值并像这样称它为checked
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
checked: false
};
};
componentWillReceiveProps( nextProps ){
//more code
this.setState({
checked: true
});
};
render() {
return(
<div id="section">
<div className="bottom-question">
<div>
<div className="onoffswitch-add pull-left">
<input type="checkbox"
name="onoffswitch"
checked={this.state.checked} />
<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>
)
}
}
答案 1 :(得分:1)
我想你想要<input required={this.state.required} />
答案 2 :(得分:1)
React有一个属性。
<input type="checkbox" name="onoffswitch" disabled={this.state.required} />
其中this.state.required
是boolean
答案 3 :(得分:0)
如果未选中复选框,您可能希望{0}}支柱为disabled
,而true
则为false
。
为此,请从存储复选框值的状态变量开始。然后添加一个在onChange
事件上触发的函数,该函数从true-&gt;切换状态。是的,反之亦然。
取消选中该复选框后,应禁用该按钮。
class MyApp extends React.Component {
constructor() {
super();
this.state = {
checkboxState: false
};
}
toggleCheckbox = () => {
this.setState({checkboxState: !this.state.checkboxState});
}
render() {
return (
<form>
<input type="checkbox" name="onoffswitch" onChange={this.toggleCheckbox} />
<input type="submit" disabled={!this.state.checkboxState} value="submit" />
</form>
);
}
}
ReactDOM.render(<MyApp />, document.getElementById("app"));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
&#13;