映射内匿名函数内的方法未定义

Method inside anonymous function inside map is undefined

本文关键字:方法 未定义 映射 函数      更新时间:2023-09-26

在这个示例React组件中,如何在消息映射中调用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 = {messages:["THANKS", "MERCI", "GRAZIE"]}
    this.myFunc = this.myFunc.bind(this)
    this.handleButtonPress = this.handleButtonPress.bind(this)
  }
  render(){
    return (
      <View>
        <Text>{this.state.message}</Text>
        {
          this.state.messages.map(function(message, index){
            return (
              <TouchableOpacity key={index} onPress={function(){ this.handleButtonPress(message) }.bind(this) }>
                <Text>Press Me</Text>
              </TouchableOpacity>
            )
          })
        }
      </View>
    )
  }
  handleButtonPress(message){
    console.log("BUTTON WAS PRESSED WITH MESSAGE: " + message)
    this.myFunc(message)
  }
  myFunc(message){
    console.log("MY FUNCTION WAS CALLED")
    this.setState({message:message})
  }
}

现在它正在抛出:undefined is not a function (evaluating 'this.handleButtonPress(message)')。为什么会这样?

问题是Array.prototype.map不会绑定this上下文,除非明确告知

如果将thisArg参数提供给map,则在调用时会将其传递给回调,用作其this值。否则,值undefined将被传递用作其this值1

由于从未指定this值,因此它是undefined,因此绑定到onPress中匿名函数的thisundefined。这抛出了错误,因为undefined中没有函数handleButtonPress。这意味着您需要将this上下文传递给map,并从文档中传递:

语法

arr.map(callback[, thisArg])

这将像这样应用:

{
    this.state.messages.map(function(message, index){
        return (
          <TouchableOpacity key={index} onPress={function(){ this.handleButtonPress(message) }.bind(this) }>
            <Text>Press Me</Text>
          </TouchableOpacity>
        )
    }, this) //Notice the `this` here, this is the optional thisArg which is used as the `this` value in the callback.
}

this是传递给map时的类。然后它将被绑定到onPress的事件处理程序(匿名函数(,然后正确调用。(注意:您可能应该在构造函数中绑定一次方法,因为如果您像现在这样做,每次触发事件时都会创建一个新方法。(


实际上,在没有通过thisArg的情况下,this的值照常确定。由于常规函数中的thiswindow(严格模式下的undefined,这是类的默认值(,所以this并不是你想象的那样