onChange function for input fields not working

时间:2019-01-09 22:17:28

标签: javascript reactjs events

Trying to change the state of input fields but onChange doesn't seem to be working and input fields are disabled (not letting me type)

constructor() {
    super();
    this.state = {
        title: '',
        length: '',
        image: '',
        source: '',
        available: '',
        date: '',
        errors: {}
    }
    this.onChange = this.onChange.bind(this);
}

onChange(e) {
    this.setState({ [e.target.name]: e.target.value });
}

<input value={this.state.length} onChange={this.onChange} type="text" 
    className="form-control" name="email" placeholder="e.g. 3:36" />

2 个答案:

答案 0 :(得分:2)

2 things :

Your setState function updates a value in the state based on the event's target node name, and here, the name ("email") does not match the value you are getting in your state (length).

The second error is that your onChange is not bound to your class, calling this.setState will return an error.

You can solve it by changing the value variable in your input :

<input value={this.state.email} onChange={this.onChange} type="text" className="form-control" name="email" placeholder="e.g. 3:36"/>

And converting onChange to an arrow function (or binding it) :

onChange = e => {
    this.setState({ [e.target.name]: e.target.value });
}

答案 1 :(得分:0)

**更新: **您的主要错误是您将输入链接到一个名为“长度”的状态变量,并且输入名称是“电子邮件”,它们应该相同。

如果您使用箭头函数,则可以使自己更轻松,根本不需要绑定到构造函数,因此,如果您这样编写函数,则:

library(dplyr)    
df %>%
  mutate(Col3 = ifelse(Col1 %in% c("A","B"),Col3,Col2))

您的构造函数和状态将如下所示:

onChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
}

而且,在JSX中,您仍然以相同的方式传递属性,如下所示:

constructor() {
     super();
 this.state = {
    title: '',
    email: '',
    image: '',
    source: '',
    available: '',
    date:'',
    errors: {}
}

}

完整的演示:

Edit 487m15996x