2017-06-29 108 views
2

我使用Material UI复选框组件,并尝试在控制台状态更改中切换状态onCheck,但是在UI中,复选标记不会切换。我弄乱了什么。复选框状态不切换。 Material UI React

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 

组件

<CheckboxInteractivity /> 
//working correctly 
<CheckboxInteractivity checked/> 
//not working 

回答

3

它之所以不与第二个案子是:

return <Checkbox 
      label="Label" 
      checked={switched} 
      onCheck={this.handleChange} 
      {...this.props} 
     /> 

将变为:

return <Checkbox 
      label="Label" 
      checked={switched} 
      onCheck={this.handleChange} 

      checked={true}      //here 

     /> 

使用两个checked属性第二将使复选框被选中为真总是与state变量无关,这就是原因。删除{...this.props}它将按预期工作。

为什么它在第一种情况下工作的是,你没有通过checked,因此checkbox将只能找到一个选中的键,它将根据该键来呈现组件。

这里不需要{...this.props},因为您已经将值存储在state中。

建议:

而是在componentWillMount生命周期的方法设置在stateprops值的设置,在只有constructor,像这样:

constructor(props){ 
    super(props); 
    this.state = { 
     switched: props.checked || false, 
    } 
} 

更新:

比方说, ,你在0​​和很少的值通过许多值因为你想要在组件中覆盖,所以你需要做的是,首先应用所有的属性,然后定义其他属性。通过这种方式,组件属性将覆盖props属性。

像这样:

return <Checkbox 
      {...this.props}    //first apply props values then other 
      label="Label" 
      checked={switched} 
      onCheck={this.handleChange}     
     /> 
+0

中,如果我想尝试添加禁用的道具,我需要{...} this.props,因为取决于该道具我设置样式情况下,只有一个问题

+1

@PalaniichukDmytro检查更新的答案,更新部分。你只需要先应用'props'值然后再应用其他值,排序将解决你的问题:) –