Javascript 复选框状态不切换。材料界面反应
我使用Material UI复选框组件,并尝试在选中时切换状态,在控制台中状态更改,但在UI中不切换,复选标记不切换。我搞砸了什么Javascript 复选框状态不切换。材料界面反应,javascript,reactjs,material-ui,Javascript,Reactjs,Material Ui,我使用Material UI复选框组件,并尝试在选中时切换状态,在控制台中状态更改,但在UI中不切换,复选标记不切换。我搞砸了什么 class CheckboxInteractivity extends React.Component { state = { switched: false, } componentWillMount() { const {checked} = this.props if (checked
class CheckboxInteractivity extends React.Component {
state = {
switched: false,
}
componentWillMount() {
const {checked} = this.props
if (checked) {
this.setState({
switched: true,
})
}
}
handleChange = (event, switched) => {
this.setState({switched: !this.state.switched})
}
render () {
const {switched} = this.state
return <Checkbox
label="Label"
checked={switched}
onCheck={this.handleChange}
{...this.props}
/>
}
}
CheckboxInteractivity.propTypes = {
checked: PropTypes.bool,
}
export default CheckboxInteractivity
类checkboxInteractive扩展了React.Component{
状态={
错,,
}
组件willmount(){
const{checked}=this.props
如果(选中){
这是我的国家({
对,,
})
}
}
handleChange=(事件,已切换)=>{
this.setState({switched:!this.state.switched})
}
渲染(){
const{switched}=this.state
返回
}
}
CheckboxInteractivity.propTypes={
选中:PropTypes.bool,
}
导出默认复选框交互性
组成部分
<CheckboxInteractivity />
//working correctly
<CheckboxInteractivity checked/>
//not working
//工作正常
//不起作用
它不适用于第二种情况的原因是:
return <Checkbox
label="Label"
checked={switched}
onCheck={this.handleChange}
{...this.props}
/>
更新:
比方说,您在props
中传递了许多值,而在组件中要覆盖的值很少,所以您需要在这里做的是,首先应用所有props
属性,然后定义其他属性。通过这种方式,组件属性将覆盖props
属性
像这样:
return <Checkbox
{...this.props} //first apply props values then other
label="Label"
checked={switched}
onCheck={this.handleChange}
/>
返回
只有一个问题,如果我想尝试添加道具禁用,我需要{…this.props},因为依赖于这个道具,我设置styles@PalaniichukDmytro检查更新的答案,更新部分。您只需先应用道具
值,然后再应用其他值,排序将解决您的问题:)
constructor(props){
super(props);
this.state = {
switched: props.checked || false,
}
}
return <Checkbox
{...this.props} //first apply props values then other
label="Label"
checked={switched}
onCheck={this.handleChange}
/>