Question: React.js - "this" undefined even after binding

Question

React.js - "this" undefined even after binding

Answers 1
Added at 2016-12-29 12:12
Tags
Question

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>
        );
    }
}
Answers
nr: #1 dodano: 2016-12-29 12:12

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'}
}
Source Show
◀ Wstecz