[英]Typescript: _this2.onClick is not a function
I use typescript for react-native development. 我使用typescript进行react-native开发。 Here List
and ListItem
are from NativeBase and ListItem
is like TouchableOpacity
component. 这里List
和ListItem
是从NativeBase和ListItem
是像TouchableOpacity
组件。
...
public onClick = () => this.props.navigation.navigate("NextScreen");
public _renderRow = (item: any) {
return (
<ListItem onPress={() => this.onClick()}>
...
</ListItem>
);
}
public render() {
return(
<List
dataArray={this.data}
renderRow={this._renderRow}
/>
);
}
When I click item, it shows following error. 当我单击项目时,它显示以下错误。
_this2.onClick is not a function. _this2.onClick不是一个函数。 (In '_this2.onClick()', '_this2.onClick' is undefined) (在'_this2.onClick()'中,'_this2.onClick'未定义)
I assume this is because onClick()
function isn't bound to component class. 我假设这是因为onClick()
函数没有绑定到组件类。 Is the function bound automatically in typescript? 函数是否在typescript中自动绑定?
How can I solve this problem? 我怎么解决这个问题?
You need to bind
the method to the components class: 您需要bind
方法bind
到组件类:
public onClick() {
this.props.navigation.navigate("NextScreen");
}
public _renderRow(item: any) {
return (
<ListItem onPress={this.onClick}>
...
</ListItem>
);
}
public render() {
return(
<List
dataArray={this.data}
renderRow={this._renderRow.bind(this)} // <---- Here
/>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.