React 组件正在更改类型为复选框的不受控制的输入

React component is changing an uncontrolled input of type checkbox

具有以下用于自定义复选框的 React 组件,其中值作为 props 从父项传递下来

export const CheckBox = (props) => {
  let closeClass;

  if (!props.hint && props.hint == "") {
    closeClass = "no-hint";
  }
  return (
    <div className={"field-wrapper checkbox-button-grouped"}>
      <label htmlFor={`checkbox_${props.value}`}>
        <input
          onChange={props.handleCheckChieldElement}
          type="checkbox"
          name={props.name}
          id={`checkbox_${props.value}`}
          className={"input-field"}
          checked={props.isChecked}
          value={props.value || ""}
        />
        <div className="label-text">
          <div className={"label-name"}>{props.label}</div>
          {props.hint && props.hint !== "" ? (
            <div className={"info-icon"}>
              <InfoIcon className={"info-icon"} />
            </div>
          ) : null}
          <div className={"hint"}>{props.hint}</div>
          <UncheckIcon className={classnames("uncheck", closeClass)} />
          <Checkmark className={"ok-icon"} />
        </div>
      </label>
    </div>
  );
};

export default CheckBox;

我不断收到以下错误

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.

在这种情况下我做错了什么?

props.isChecked可能是null或者undefined,可以这样解决:

checked={props.isChecked || false}

Warning: A component is changing an uncontrolled input of type checkbox to be controlled

如果您收到此错误,则表示您提供给输入字段的值未由您的 onChange 函数更新。

分配给任何输入的值状态只能通过 onChange 函数修改,否则您会收到此警告。

也有可能在执行 onChange 操作后立即未定义该值。

根据您的情况声明

isChecked as a boolean with initial value as false or true as you like.

如果你正在使用钩子

const [isChecked, setIsChecked] = React.useState(false);

对于 class 组件

this.state = {
   isChecked: false
}

这是代码沙箱中的工作代码code