React a component is changing an uncontrolled input of type checkbox to be controlled

后端 未结 3 2238
眼角桃花
眼角桃花 2021-02-19 06:33

react gives me a warning: \"A component is changing an uncontrolled input of type checkbox to be controlled. Input elements should not switch from uncontrolled to controlled (or

相关标签:
3条回答
  • 2021-02-19 07:16

    If your state is initialized with props.value being null React will consider your Checkbox component to be uncontrolled.

    Try setting your initial state so that value is never null.

    this.state = { value: props.value || "" };
    
    0 讨论(0)
  • 2021-02-19 07:21

    If you are using a checkbox react won't like a string either so instead try

    this.state = { checkboxValue: props.checkboxValue || false };
    
    0 讨论(0)
  • 2021-02-19 07:29

    Something worth noting about the above code snippet. When you set a state in the constructor from props, it is always best to set the state to a "controlled" value i.e. a tangible value such as an int, float, string, array, map, etc. The error you are getting is the result of props.value being set to null

    So, Consider setting your constructor state like this:

    this.state = {
        value: props.value ? props.value : 'empty'
    }
    

    What is happening here is it is checking if props.value has a value, if it does it sets the state to props.value, if props.value is null, it sets the state to the string: `'empty'

    0 讨论(0)
提交回复
热议问题