【发布时间】:2019-05-23 15:29:00
【问题描述】:
编辑:这个问题被一些用户标记为重复。不确定他们是否在这样做之前阅读过它。如果有人这样做,请澄清这是在何种意义上重复。
我有一个复选框组件:
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>
);
}
}
它不会返回任何错误。为什么?
【问题讨论】:
-
link 的副本,受控(使用状态)
-
不确定是否有人在将其标记为重复之前阅读了我的示例。
-
@tarzenchugh 关于为什么重复的任何解释?
-
@rayhatfield 想要了解详情
标签: javascript reactjs controlled-component