React Native this2.'function' 不是函数 [英] React Native this2.'function' is not a function
问题描述
我的 React Native 组件有问题.
sayHi = (s) =>{console.log('嘿' + s)}renderListItem(item, i) {返回 (<TouchableOpacity键={i}style={styles.listItem}onPress={() =>{ this.sayHi('bob') }}><文本>{项目}</文本></TouchableOpacity>)}使成为() {this.sayHi('帕特里克')const { list } = this.props返回 (<查看>{list.map(this.renderListItem)}</查看>)}
在 renderListItem
中出现错误 _this2.sayHi is not a function.
在网上搜索过,但大多数帖子不适合我的情况;我看了这篇文章,但我已经有了箭头函数,所以这不是上下文问题.
函数控制台在 render()
中记录得很好.我试图在构造函数中绑定 this
但我仍然收到错误.
Array#map
在不同的上下文中执行回调,所以 this
没有正确绑定.根据文档:
语法
var new_array = arr.map(callback[, thisArg])
参数
[...]
thisArg
可选.执行回调时用作 this
的值.
[...]
如果thisArg
参数提供给map
,它将用作回调的this
值.否则,值 undefined
将用作它的 this
值.
您可以将 this
上下文作为第二个参数传递给 Array#map
:
{list.map(this.renderListItem, this)}
或者,直接使用Function#bind
:
{list.map(this.renderListItem.bind(this))}
最后,您可以使用箭头函数:
{list.map((item, i) => this.renderListItem(item, i))}
虽然我个人会选择第一个选项.
I have a problem with my React Native Component.
sayHi = (s) => {
console.log('hey' + s)
}
renderListItem(item, i) {
return (
<TouchableOpacity
key={i}
style={styles.listItem}
onPress={() => { this.sayHi('bob') }}>
<Text>{item}</Text>
</TouchableOpacity>
)
}
render() {
this.sayHi('patrick')
const { list } = this.props
return (
<View>
{list.map(this.renderListItem)}
</View>
)
}
In renderListItem
I get an error _this2.sayHi is not a function.
Searched online but most posts do not fit my situation; I took a look at this post but I already have an arrow function so it's not a context problem.
The function console logs just fine in the render()
.
I tried to bind the this
in the constructor but I still get the error.
Array#map
executes the callback in a different context so this
isn't correctly bound. Per the documentation:
Syntax
var new_array = arr.map(callback[, thisArg])
Parameters
[...]
thisArg
Optional. Value to use as
this
when executing callback.[...]
If a
thisArg
parameter is provided tomap
, it will be used as callback'sthis
value. Otherwise, the valueundefined
will be used as itsthis
value.
You can pass this
context as the second argument to Array#map
:
{list.map(this.renderListItem, this)}
Or, use Function#bind
directly:
{list.map(this.renderListItem.bind(this))}
Finally, you could use an arrow function:
{list.map((item, i) => this.renderListItem(item, i))}
Though I would choose the first option personally.
这篇关于React Native this2.'function' 不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!