编辑:这个问题被一些用户标记为重复。不确定他们是否在这样做之前阅读过它。如果有人这样做,请澄清在何种意义上这是重复的。
我有一个复选框组件:
class Checkbox extends Component {
onChange = (e) => {
if (this.props.input) {
this.props.input.onChange(e.target.checked);
} else if (this.props.onChange) {
this.props.onChange(e.target.checked, this.props.id);
}
};
render() {
const { input, value, className, label } = this.props;
let inputValue = (input && input.value) || value;
return (
<div className={'Checkbox' + (className ? ' Checkbox--' + className : '')}>
<input
className="Checkbox-input"
type="checkbox"
onChange={this.onChange}
checked={inputValue}
/>
<span className="Checkbox-helper" />
<span className="Checkbox-label" htmlFor="">
{label}
</span>
</div>
);
}
}
该组件在值更改时返回错误。
警告:组件正在更改要控制的复选框类型的不受控制的输入。输入元素不应从不受控切换到受控(反之亦然)。决定在组件的生命周期内使用受控输入元素还是不受控输入元素。
但如果我更换:
let inputValue = (input && input.value) || value;
和
let inputValue = value;
if (input) {
inputValue = input.value;
}
像这样:
class Checkbox extends Component {
onChange = (e) => {
if (this.props.input) {
this.props.input.onChange(e.target.checked);
} else if (this.props.onChange) {
this.props.onChange(e.target.checked, this.props.id);
}
};
render() {
const { input, value, className, label } = this.props;
let inputValue = value;
if (input) {
inputValue = input.value;
}
return (
<div className={'Checkbox' + (className ? ' Checkbox--' + className : '')}>
<input
className="Checkbox-input"
type="checkbox"
onChange={this.onChange}
checked={inputValue}
/>
<span className="Checkbox-helper" />
<span className="Checkbox-label" htmlFor="">
{label}
</span>
</div>
);
}
}
它不返回任何错误。为什么?