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

查看:22
本文介绍了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 正在将文本类型的不受控制的输入更改为受控.输入元素不应从不受控制切换到控制(反之亦然).决定使用受控或组件生命周期内不受控制的输入元素

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.

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

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