2016-10-17 48 views
2

在本示例的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)')。为什么?

+0

这里又一次,'map'内的'this'是未定义的,除非显式传递。 – Li357

+0

脂肪箭头函数不会解决这个问题? '()=>' – Maxwelll

回答

6

问题是Array.prototype.map没有绑定this上下文,除非明确告知。从文档:

如果thisArg参数提供给map,它会通过调用时,用作this值回调。否则,将传递值undefined作为其值。

因为你永远不指定this值,它是undefined,做这样绑定匿名函数onPressthisundefined。这会引发错误,因为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值如常确定。由于this的常规功能是windowundefined处于严格模式,这是默认的类别),因此this不是您认为的那样。

+0

令人惊叹。再次感谢@ andrew-li。将标记正确。 – s2t2