React.js - 即使绑定后“这个”也未定义

IT技术 javascript reactjs this bind
2021-05-20 18:02:42

我试图捕获输入的onChange事件并使用新值调用setState,但是一旦我输入输入,我就会得到:

Uncaught TypeError: Cannot read property 'setState' of undefined

虽然我打过电话

 this.handleChange.bind(this)

在构造函数中

索引.js

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

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

应用程序.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个回答

this.handleChange.bind(this)绑定- 返回对函数的新引用分配this.handleChange.,因为this.handleChange必须引用返回的新函数.bind

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