javascript - 警告:组件正在更改要控制的文本类型的不受控输入
问题描述
完整的错误:
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)
我的代码:
//Form.js
componentDidMount = () => {
let state = {};
const { inputProps } = this.props;
//example for inputProps: {
// {nameInput: {element: Input/*Input.js*/, value: "initial value"}}
//}
Object.keys(inputProps).forEach(key => {
const input = inputProps[key];
const { value } = input;
state[key] = {
...input,
value,
onChange: this.inputChange(key)
}
})
this.setState(state)
}
inputChange = key => event => this.setState({
[key]: {
...this.state[key],
value: event.target.value
}
})
inputs = () => Object.keys(this.state).map(key => {
const input = this.state[key];
const { element, typeCheck, ...props } = input;
return React.createElement(element, props);
})
//Input.js
//the error comes after typeChecking in Form.js I just didn't wanted to show unnecessary code
const Input = ({error, ...props}) => <div className="inputContainer">
{React.createElement("input", props)}
<p className="inputError">{error || ""}</p>
</div>
所以这里发生的是我有一个组件Form
,它接受一个对象,因为它是定义需要创建哪些输入的道具。当它挂载时,它会处理输入属性并将其设置为状态。这有点偷偷摸摸,因为我们可能会获得价值作为输入的道具,但我们将其置于表单的状态。此外,我们还将值赋予 Input 元素,因此它是受控的,如果输入发生变化,则触发在 Form 中调用的函数,并将值设置为它自己的状态,然后将更新后的值返回给 Input . 所以看起来输入是受控的,但我仍然得到错误。一切正常,所以输入获取更新的值,并发送更改的输入,我只是得到错误,这很烦人。
解决方案
如果输入值初始化为 null 或 undefined,您将始终收到此错误。您可以通过将输入值设置为空字符串来避免它。
推荐阅读
- jquery - 未捕获的 ReferenceError:使用 multiDatePicker 库时未定义 $?
- amazon-web-services - 来自另一个区域的 EC2 的 Aurora 连接
- gatsby - 使用 gatsby-source-contentful 时如何设置 GATSBY_CONTENTFUL_OFFLINE 标志
- ignite - Apache Ignite 节点无法集群 - 通信问题
- python-3.x - 文本规范化:Python 中的文本相似性。如何规范文本拼写不匹配?
- postgresql - 如何在 PostgreSQL 中获取包括今天在内的上周日?
- r - 计算一行与每组其余数据之间的差异
- java - 如何标记使用我的程序创建的文件
- aspnetboilerplate - 为什么这会引发 PK 重复错误?
- codeigniter - 如何在php javascript中的特定日子禁用按钮