React从非受控组件切换到受控组件错误

所谓受控组件,是将<input>,<textarea>, 和 <select>这类表单元素的状态信息交于 React 进行维持,而非受控组件是由这些表单元素标签自身维持。

在 React 中,如果出现了从非受控组件到受控组件的变化,就会抛出如下警告

index.js:1446 Warning: A component is changing an uncontrolled input of type checkbox to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.

例如如下示例

export class Checkbox extends Component {
  static defaultProps = {
    label: ""
  };

  constructor(props) {
    super(props);
    this.state = {
      checked: props.checked,
      disable: props.disable
    };
  }

  handleChange(checked) {
    this.setState({
      checked: !checked
    });
  }

  render() {
    const { disable, checked } = this.state;
    const { label } = this.props;
    return (
      <div className="demo-checkbox-box clearfix">
        <div className="checkboxs">
          <label className="check-label">{label}</label>
          <input
            {...this.otherProps}
            type="checkbox"
            className="check-input"
            disabled={disable}
            checked={checked}
            onChange={() => this.handleChange(checked)}
          />
        </div>
      </div>
    );
  }
}

这是一个 checkbox 组件,通过点击可以控制其选中。但是,此处代码示例点击选项按钮时,在控制台就会抛出上述错误警告。这是因为,checked属性并没有为其指定默认值,所以 React 会认为它是一个非受控组件,此时,如果点击了该按钮,会触发onChange事件,则会通过setStatechecked赋值,这就相当于从非受控变为受控。

要解决这个问题,只需要为checked指定默认值即可。

static defaultProps = {
  label: "",
  checked: false
};

官方文档的相关介绍:

非受控组件:https://react.docschina.org/docs/uncontrolled-components.html
受控组件:https://react.docschina.org/docs/forms.html

如果您觉得本文对您有用,欢迎捐赠或留言~
微信支付
支付宝

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注