React- Cannot read property 'setState' of undefined

戏子无情 提交于 2019-12-03 12:23:56

In these event handlers, e.target is the <input> which triggered the event.

onChangeName(e) {
    //this.state.name = e.target.name
    this.setState({ name: e.target.name});
}

onChangePassword(e) {
    //this.state.password = e.target.name
    this.setState({ password: e.target.password });
}

You get an input's value by using its value property:

onChangeName(e) {
    this.setState({name: e.target.value});
}

onChangePassword(e) {
    this.setState({password: e.target.value});
}

You also need to ensure this is bound properly, as per the commented-out code in your constructor.


If you give your inputs suitable name props, you replace these with a single onChange handler:

constructor(props) {
  super(props)
  // ...
  this.onChange = this.onChange.bind(this)
}

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

render() {
  // ...
  <input type="text" name="name" value={this.state.name} onChange={this.onChange}/>
  <input type="password" name="password" value={this.state.password} onChange={this.onChange}/>
  // ...
}

edit

If you're going to follow the pattern of binding in the constructor, make sure you use a correct constructor invocation:

constructor (props) {
    super(props)

Notice props inside the constructor.

original answer

Since it appears you're using ES6 component definitions, you should bind to this within the rendered component:

<input type="text" value={this.state.name} onChange={this.onChangeName.bind(this)} />

You don't need to define this stuff in the constructor:

 //this doesn't work
 //this.onChangeName = this.onChangeName.bind(this);
 //this.onChangePassword = this.onChangePassword.bind(this);

It also appears that maybe you've left out some code in your example, so I'm not sure if you were trying to get rid of the unnecessary parts for the sake of example or what, but make sure your component is properly structured.

If you use an arrow function then you won't need to bind.

onNameChange = (e)=> {
this.setState({name:e.target.value});
}

onPasswordChange = (e) => {
this.setState({password:e.target.value});
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!