本文介绍了React - 更改不受控制的输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的反应组件,我相信它有一个受控输入:

I have a simple react component with the form which I believe to have one controlled input:

import React from 'react';

export default class MyForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {}
    }

    render() {
        return (
            <form className="add-support-staff-form">
                <input name="name" type="text" value={this.state.name} onChange={this.onFieldChange('name').bind(this)}/>
            </form>
        )
    }

    onFieldChange(fieldName) {
        return function (event) {
            this.setState({[fieldName]: event.target.value});
        }
    }
}

export default MyForm;

当我运行我的应用程序时,我收到以下警告:

When I run my application I get the following warning:

警告:MyForm 正在将不受控制的文本类型输入更改为受控.输入元素不应从不受控制切换到控制(反之亦然).决定使用受控或组件生命周期内不受控制的输入元素

我相信我的输入是受控制的,因为它具有价值.我想知道我做错了什么?

I believe my input is controlled since it has a value. I am wondering what am I doing wrong?

我正在使用 React 15.1.0

I am using React 15.1.0

推荐答案

要控制输入,其值必须对应于状态变量的值.

For an input to be controlled, its value must correspond to that of a state variable.

在您的示例中最初不满足该条件,因为 this.state.name 最初未设置.因此,输入最初是不受控制的.一旦 onChange 处理程序第一次被触发,this.state.name 就会被设置.此时,满足上述条件,输入被认为是受控的.这种从不受控制到受控制的转变产生了上述错误.

That condition is not initially met in your example because this.state.name is not initially set. Therefore, the input is initially uncontrolled. Once the onChange handler is triggered for the first time, this.state.name gets set. At that point, the above condition is satisfied and the input is considered to be controlled. This transition from uncontrolled to controlled produces the error seen above.

通过在构造函数中初始化this.state.name:

By initializing this.state.name in the constructor:

例如

this.state = { name: '' };

输入将从一开始就受到控制,从而解决了问题.有关更多示例,请参阅 React Controlled Components.

the input will be controlled from the start, fixing the issue. See React Controlled Components for more examples.

与此错误无关,您应该只有一个默认导出.你上面的代码有两个.

Unrelated to this error, you should only have one default export. Your code above has two.

这篇关于React - 更改不受控制的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 13:02
查看更多