React.js - “this” undefined even after binding

2019-02-27 09:01发布

问题:

I am trying to capture onChange event of the input and calling setState with the new value, but as soon as I type in the input I get:

Uncaught TypeError: Cannot read property 'setState' of undefined

Even though I have called

 this.handleChange.bind(this)

in the constructor

index.js

import React  from 'react'
import * as ReactDOM from "react-dom";
import App from './App'

ReactDOM.render(
    <App />,
    document.getElementById('root')
);

App.js

import * as React from "react";
export default class App extends React.Component {
    constructor(props) {
        super(props)
        this.handleChange.bind(this)
        this.state = {contents: 'initialContent'}
    }


    handleChange(event) {
       this.setState({contents: event.target.value})
    }


    render() {
        return (
            <div>
                Contents = {this.state.contents}
                <input type="text" onChange={this.handleChange}/>
            </div>
        );
    }
}

回答1:

Assign this.handleChange.bind(this)(bind - returns new reference to function) to this.handleChange., because this.handleChange have to refer to new function which returns .bind

constructor(props) {
  super(props)
  this.handleChange = this.handleChange.bind(this)
  this.state = {contents: 'initialContent'}
}