admin管理员组

文章数量:1315033

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>
        );
    }
}

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>
        );
    }
}
Share Improve this question asked Dec 29, 2016 at 11:29 simplfuzzsimplfuzz 12.9k25 gold badges88 silver badges140 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 14

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'}
}

本文标签: javascriptReactjsquotthisquot undefined even after bindingStack Overflow