簡體   English   中英

警告:組件正在更改要控制的文本類型的不受控制的輸入

[英]Warning: A component is changing an uncontrolled input of type text to be controlled

完全錯誤: 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) 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 ,該Form接受一個對象,因為它支持定義需要創建的輸入。 掛載后,它將處理輸入屬性並將其設置為狀態。 這有點偷偷摸摸,因為我們可能會獲得價值作為投入的支柱,但我們將其置於表單的狀態。 另外,我們還將值賦給Input元素,以便對其進行控制,如果輸入發生更改,則會觸發在Form中調用的函數,並將該值設置為其自己的狀態,然后將更新后的值返回給Input 。 因此,似乎輸入受到控制,但是我仍然收到錯誤。 一切正常,因此輸入獲取更新后的值,並發送更改后的輸入,我剛得到錯誤,這很煩人。

如果輸入值初始化為null或未定義,則始終會出現此錯誤。 您可以通過將輸入值設置為空字符串來避免這種情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM