复选框状态不切换。材质 UI 反应

Pal*_*tro 4 javascript reactjs material-ui

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

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
Run Code Online (Sandbox Code Playgroud)

成分

<CheckboxInteractivity /> 
//working correctly
<CheckboxInteractivity checked/>
//not working 
Run Code Online (Sandbox Code Playgroud)

May*_*kla 5

它不适用于第二种情况的原因是:

return <Checkbox
            label="Label"
            checked={switched}
            onCheck={this.handleChange}
            {...this.props}
       />
Run Code Online (Sandbox Code Playgroud)

会变成:

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

            checked={true}                     //here

       />
Run Code Online (Sandbox Code Playgroud)

您正在使用两个checked属性,第二个将使复选框始终处于选中状态,无论state变量为何。删除{...this.props}它会按预期工作。

为什么它在第一种情况下工作是,你没有通过checked所以checkbox只会找到一个检查的键,它会在此基础上呈现组件。

这里{...this.props}不是必需的,因为您已经将值存储在state.

建议:

而不是在生命周期方法中设置props值,只设置它,像这样:statecomponentWillMount constructor

constructor(props){
    super(props);
    this.state = {
        switched: props.checked || false,
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:

比方说,您props要在组件中传递许多值,而要在组件中覆盖的值很少,因此您在这里需要做的是,首先应用所有props属性,然后定义其他属性。通过这种方式,组件属性将覆盖props属性。

像这样:

return <Checkbox
            {...this.props}                //first apply props values then other
            label="Label"
            checked={switched}
            onCheck={this.handleChange}                
       />
Run Code Online (Sandbox Code Playgroud)