首页 > 解决方案 > React 组件正在更改复选框类型的不受控制的输入

问题描述

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

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.

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

标签: reactjscheckboxcomponentswarnings

解决方案


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

checked={props.isChecked || false}

推荐阅读