地图内部匿名函数内部的方法未定义 [英] Method inside anonymous function inside map is undefined

查看:52
本文介绍了地图内部匿名函数内部的方法未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此示例React组件中,如何在消息映射内调用 handleButtonPress

How does one invoke handleButtonPress inside the message map in this example React component?

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不是函数(评估'this.handleButtonPress(message)')。为什么呢?

Right now it's throwing: undefined is not a function (evaluating 'this.handleButtonPress(message)'). Why is that so?

推荐答案

问题是 Array.prototype.map 不会绑定上下文,除非明确告知。从文档中:

The problem is that Array.prototype.map doesn't bind a this context unless explicitly told to. From the documentation:


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

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

由于您从未指定值,因此它是未定义,因此执行<$ c在 onPress 中绑定到匿名函数的$ c> this undefined 。之所以抛出错误,是因为没有 undefined 的函数 handleButtonPress 。这意味着您需要将上下文传递给 map ,并从文档中传递:

Since you never specify a this value, it is undefined, and doing thus the this that is bound to the anonymous function in onPress is undefined. That throws the error because there is no function handleButtonPress of undefined. This means you need to pass a this context to map, and from the documentation:


语法

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 是通过时的类到地图。然后,它将绑定到 onPress 的事件处理程序(匿名函数),然后正确调用。 (注意:您可能应该在构造函数中绑定一次方法,因为如果像现在这样进行操作,则每次触发事件时都会创建一个新方法。)

The this is the class when passed to map. It will then be bound to onPress's event handler (the anonymous function) and then call correctly. (Note: You should probably bind your methods once in the constructor because if you do it as you do now, a new method will be created every time the event is triggered.)

1 实际上,在没有传递 thisArg 的情况下, this 值照常确定。由于常规功能中的 this window (严格来说, undefined 模式,这是类的默认设置),不是您想的那样。

1Actually, without a thisArg passed, the this value is determined as usual. Since this in regular functions is window (undefined in strict mode, which is default for classes), this isn't what you think it is.

这篇关于地图内部匿名函数内部的方法未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆