作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我使用 React + TypeScript + Mobx。我用输入制作了表格,一切正常,但浏览器给出了错误。我做错了什么?
Warning: A component is changing an uncontrolled input of type text 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.
表格:
@observer
export class SearchForm extends React.Component {
@observable
private _inputText: string;
submitForm = (event: SyntheticEvent<HTMLFormElement>) => {
event.preventDefault();
}
render() {
return (
<form onSubmit={this.submitForm}>
<InputField
value={this._inputText}
onChange={action((value: string) => this._inputText = value)}
/>
</form>
);}}
输入:
interface Props {
value: string;
onChange: (inputText: string) => void;
}
@observer
export class InputField extends React.Component<Props> {
onChange = (event: SyntheticEvent<HTMLInputElement>) => {
this.props.onChange(event.currentTarget.value);
}
render() {
return (
<div>
<input
type="text"
value={this.props.value}
onChange={this.onChange}
/>
</div>
);
}
}
最佳答案
React 的输入是受控/不受控的,这取决于输入中是否存在 value prop。您传递的是值(value)支柱,但是 _inputText
开始为 undefined
.当输入的值开始未定义时,React 将始终以不受控模式启动输入。
输入后,_inputText
不再是未定义的,并且输入切换到受控模式,您会收到警告。
对于您的情况,修复很简单;只需初始化 _inputText
到空字符串:
@observable
private _inputText: string = '';
您还可以调整您的 <InputField />
强制未定义的值属性为空字符串:
render() {
return (
<div>
<input
type="text"
value={this.props.value == null ? '' : this.props.value}
onChange={this.onChange}
/>
</div>
);
}
关于reactjs - react -Mobx 警告 : A component is changing an uncontrolled input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50715760/
我是一名优秀的程序员,十分优秀!