反应受控输入无法输入[onChange]

时间:2017-12-01 07:56:36

标签: javascript reactjs react-redux

很抱歉,如果这听起来像是一个重复的问题,我已经检查了现有的答案,但似乎没有一个能解决我的问题。

我最初设置受控输入的值,例如value = {this.props.someValue}(来自API)

稍后,我试图让用户在表单上键入值

   class ProfilePage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            name: "",
            lastname: "",
            errors : ""
        };
        this.handleOnchange = this.handleOnchange.bind(this);
    }
    handleInputChange = event => {
        const { target } = event;
        this.setState({
            [target.name]: target.value,
            errors: errors
        });
    };
    handleOnchange(event) {
        const { target } = event;
        this.setState({
            [target.name]: target.value
        });
    }

    render(){
    let firstName = [];
    let lastName = [];
    if (this.props.profile) {
        firstName = this.props.profile.first_name;
        lastName = this.props.profile.last_name;

    }
    return (
            <div class="container">

                        <label for="first-name">First Name</label>
                        <input
                            type="text"
                            placeholder="First Name"
                            name="name"
                            value={firstName.value}
                            onBlur={this.handleInputChange}
                            onChange={this.handleOnchange.bind(this)}
                            className={
                                errors && errors.name
                                    ? "inputError"
                                    : "inputValid"
                            }
                        />
                </div>
    )
      }

}

我的onChange事件成功触发,但它不允许我在输入框中输入任何内容。我错过了什么?

2 个答案:

答案 0 :(得分:2)

value逻辑错了。每当this.state.name更改时,您仍然会将this.props.profile.first_name作为值发送。

onChange更新状态,重新渲染时需要检查它是否有价值。

我的建议是坚持state价值和&#34;忽略&#34;关于渲染方法的this.props.profile

一种可能的解决方案是在构造函数中将其交给它:

constructor(props) {
  super(props)

  this.state = {
    ...
    name: this.props.profile ? this.props.profile.first_name.value : ''
  }
}

答案 1 :(得分:0)

每次handleOnchange函数运行时,都会重新呈现您的表单,因为this.setState({...})调用了该表单。到目前为止这是正确的,但您必须手动更新输入value。目前,您的输入字段会在每次重新渲染时重新获取value firstname.value,这是this.props的静态内容,这就是值永远不会改变的原因。

您只需将输入value设置为handleOnchange函数中要更新的状态变量,例如this.state.name。此外,您必须使用要在加载时显示的值初始化构造函数中的状态变量(不像现在那样使用空字符串)。在您的示例中,这意味着:

constructor(props) {
    super(props);
    this.state = {
        name: props.profile.first_name.value,
        lastname: "",
        errors : ""
    };
    this.handleOnchange = this.handleOnchange.bind(this);
}

此外,您正在对this函数handleOnchange进行两次绑定,一次在构造函数中,一次在输入字段赋值中。只在构造函数中完成它就足够了,因为它是这样做的首选方式。考虑到这一点,您可以在输入字段中分配功能,如:onChange={this.handleOnchange}

相关问题