映射内匿名函数内的方法未定义
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
上下文,除非明确告知
如果将
thisArg
参数提供给map
,则在调用时会将其传递给回调,用作其this值。否则,值undefined
将被传递用作其this值1
由于从未指定this
值,因此它是undefined
,因此绑定到onPress
中匿名函数的this
是undefined
。这抛出了错误,因为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
是window
(严格模式下的undefined
,这是类的默认值(,所以this
并不是你想象的那样
相关文章:
- 骨干's Router.execute(callback,args,name)方法获取未定义的名称
- React路由器错误-'无法调用方法'getRouteAtDepth'的未定义'
- 使用javascript ajax post方法的未定义偏移PHP错误
- jQuery验证器添加方法未定义
- 定义的静态方法未定义
- jQuery Validate() 和 Valid() 方法未定义或不起作用
- 为什么内部函数中当前对象的方法未定义
- 如何解决“不能调用方法...未定义“错误
- 得到"无法调用方法..未定义的“;JavaScript和Mustache出现错误
- JavaScript方法未定义
- initialize()方法未定义
- ExpressJS PUT方法未定义的对象问题
- JavaScript - Prototype方法未定义
- 映射内匿名函数内的方法未定义
- 在事件处理程序中调用方法未定义
- 在setTimeOut函数中传递多个参数会抛出Uncaught ReferenceError:方法未定义(匿名函数)
- Javascript对象方法未定义
- app()方法未定义
- 未捕获的类型错误:不能调用方法'未定义使用Ckeditor
- QuickTime对象的SetURL方法未定义