Ger*_*áth 3 javascript reactjs
完整错误:
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>
Run Code Online (Sandbox Code Playgroud)
所以这里发生的事情是我有一个组件Form,它接受一个对象,因为它是定义需要创建哪些输入的道具。当它确实挂载时,它会处理输入属性并将其设置为它的状态。这有点偷偷摸摸,因为我们可能会获得价值作为输入的道具,但我们将其置于 Form 的状态。此外,我们还将值赋予 Input 元素,因此它是受控的,如果输入发生变化,则触发在 Form 中调用的函数,并将值设置为它自己的状态,然后将更新后的值返回给 Input . 所以看起来输入是受控的,但我仍然收到错误消息。一切正常,因此输入获取更新的值,并发送更改后的输入,我只是收到错误,这很烦人。
| 归档时间: |
|
| 查看次数: |
1562 次 |
| 最近记录: |