地图内匿名函数内的方法未定义

Method inside anonymous function inside map is undefined

在此示例 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 上下文,除非明确告知。来自文档:

If a thisArg parameter is provided to map, it will be passed to callback when invoked, for use as its this value. Otherwise, the value undefined will be passed for use as its this value.1

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

Syntax

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

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


1实际上,如果没有通过 thisArgthis 值将照常确定。由于 this 在常规函数中是 windowundefined 在严格模式下,这是 classes 的默认值),this 不是你想的那样.