绑定后甚至未定义

绑定后甚至未定义

本文介绍了React.js - “this”绑定后甚至未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

即使我已经打电话

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


推荐答案

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

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

这篇关于React.js - “this”绑定后甚至未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 11:07