首页 文章

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

提问于
浏览
-2

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

我最初设置一个受控输入的值,如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 回答

  • 2

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

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

    我的建议是在渲染方法上坚持 state 值和"ignore" this.props.profile .

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

    constructor(props) {
      super(props)
    
      this.state = {
        ...
        name: this.props.profile ? this.props.profile.first_name.value : ''
      }
    }
    
  • 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);
    }
    

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

相关问题