React.js - “this”即使在绑定后也未定义

时间:2016-12-29 11:29:57

标签: javascript reactjs this bind

我正在尝试捕获输入的 onChange 事件并使用新值调用 setState ,但是只要输入输入,我就会得到:

Uncaught TypeError: Cannot read property 'setState' of undefined

即使我已经打电话了

 this.handleChange.bind(this)

在构造函数

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 个答案:

答案 0 :(得分:9)

this.handleChange.bind(this) bind - 返回对函数的新引用)分配给this.handleChange。,因为{{ 1}}必须引用返回this.handleChange

的新函数
.bind