【发布时间】:2019-04-17 09:52:55
【问题描述】:
完整的错误:
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 .所以看起来输入是受控的,但我仍然得到错误。一切正常,所以输入获取更新的值,并发送更改的输入,我只是得到错误,这很烦人。
【问题讨论】:
标签: javascript reactjs