Javascript 事件处理程序内的调用方法未定义

Javascript 事件处理程序内的调用方法未定义,javascript,reactjs,react-native,es6-class,Javascript,Reactjs,React Native,Es6 Class,handleButtonPress功能在以下示例中不需要参数时工作 import React, { Component } from 'react'; import {View, Text, TouchableOpacity} from 'react-native'; export default class MyComponent extends Component { constructor(props){ super(props) this.state = {mess

handleButtonPress
功能在以下示例中不需要参数时工作

import React, { Component } from 'react';
import {View, Text, TouchableOpacity} from 'react-native';

export default class MyComponent extends Component {
  constructor(props){
    super(props)
    this.state = {message:"HELLO"}
    this.myFunc = this.myFunc.bind(this)
    this.handleButtonPress = this.handleButtonPress.bind(this)
  }

  render(){
    return (
      <View>
        <Text>{this.state.message}</Text>
        <TouchableOpacity onPress={this.handleButtonPress}>
          <Text>Press Me</Text>
        </TouchableOpacity>
      </View>
    )
  }

  handleButtonPress(){
    console.log("BUTTON WAS PRESSED")
    this.myFunc()
  }

  myFunc(){
    console.log("MY FUNCTION WAS CALLED")
    this.setState({message:"GOODBYE"})
  }

}

但是还有其他/更好的方法吗?

因为有一个匿名函数,所以里面的
上下文是全局
窗口
对象。由于不存在
handleButtonPress
按钮,它会抛出一个错误,即
undefined
不是一个函数。您的解决方法之所以有效,是因为
仍然引用匿名函数之外的类,因此允许您将其引用分配给
handlePress
并调用它

为了解决这个问题,您可以使用它来补充函数的
this
上下文。从链接的文档中:

bind()
方法创建一个新函数,调用该函数时,将其
this
关键字设置为提供的值

您可以这样在此处应用它:

<TouchableOpacity onPress={function() { this.handleButtonPress("GOODBYE") }.bind(this)}>

这完全摆脱了匿名函数,但是当您在
handleButtonPress
方法中使用它时,
This
仍然必须传入
bind

由于存在匿名函数,因此
This
中的上下文是全局
窗口
对象。由于不存在
handleButtonPress
按钮,它会抛出一个错误,即
undefined
不是一个函数。您的解决方法之所以有效,是因为
仍然引用匿名函数之外的类,因此允许您将其引用分配给
handlePress
并调用它

为了解决这个问题,您可以使用它来补充函数的
this
上下文。从链接的文档中:

bind()
方法创建一个新函数,调用该函数时,将其
this
关键字设置为提供的值

您可以这样在此处应用它:

<TouchableOpacity onPress={function() { this.handleButtonPress("GOODBYE") }.bind(this)}>

这完全摆脱了匿名函数,但是当您在
handleButtonPress
方法中使用它时,
This
仍然必须传入
bind

This
在匿名函数中把它搞砸了。如果您说它应该是:
onPress={function(){handleButtonPress(“再见”)}
。。。抛出:
找不到变量:handleButtonPress
这个匿名函数内部的
把它搞砸了。如果你说应该是:
onPress={function(){handleButtonPress(“再见”)}
。。。抛出:
找不到变量:handleButtonPress
onPress={function(){this.handleButtonPress(“再见”).bind(this)}}
抛出与没有绑定时相同的错误:
未定义不是函数(计算'this.handleButtonPress(“再见”)
ooh你是说它应该是
onPress={function(){this.handleButtonPress(“再见”)}.bind(this)}
是的。谢谢!@s2t2没问题,很乐意帮助:)
onPress={function(){this.handleButtonPress(“再见”).bind(this)}}
抛出与没有绑定时相同的错误:
未定义不是函数(计算'this.handleButtonPress(“再见”))
ooh你是说它应该是
onPress={function(){this.handleButtonPress(“再见”)}.bind(this)}
?是的。谢谢!@s2t2没问题,很高兴能帮上忙:)
<TouchableOpacity onPress={function() { this.handleButtonPress("GOODBYE") }.bind(this)}>
<TouchableOpacity onPress={this.handleButtonPress.bind(this, "GOODBYE")}>