reactjs - 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.
在这种情况下我做错了什么?
解决方案
props.isChecked
可能是 null 或 undefined,你可以这样解决它:
checked={props.isChecked || false}
推荐阅读
- java - Spring 教程:创建在类路径资源中定义的名称为“entityManagerFactory”的 bean 时出错
- java - 单例多态性
- javascript - Javascript:用一个简单的功能从其他主页访问数据(没有 Ajax,没有 jQuery)
- git - 将本地存储库添加到远程存储库
- c++ - 如何使用 OpenMP 并行化此矩阵乘以向量运算?
- c# - C# Api Get Route 无法接收字符串集合。在传输数据时需要帮助
- python - 将无向 NetworkX 图变为有向 NetworkX 图
- simulation - 将 omnet++ 时钟与系统时钟对齐
- typescript - 异步笑话断言没有失败测试,但断言错误打印在测试输出中
- java - 包含在 Java 中无法正常工作的方法