反应 - 改变不受控制的输入 [英] React - changing an uncontrolled input

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

问题描述

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

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正在将一个不受控制的text类型输入更改为
控制。输入元素不应从不受控制的切换到
控制(反之亦然)。决定在组件的生命周期内使用受控或
非受控输入元素

Warning: MyForm is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component

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

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

推荐答案


我相信我的输入是有控制的,因为它有一个值。

I believe my input is controlled since it has a value.

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

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.

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

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆