打字稿:_this2.onClick 不是函数

Typescript: _this2.onClick is not a function

我使用 typescript 进行 react-native 开发。 这里 ListListItem 来自 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}
        />
   );
}

当我点击项目时,它显示以下错误。

_this2.onClick is not a function. (In '_this2.onClick()', '_this2.onClick' is undefined)

我认为这是因为 onClick() 函数未绑定到组件 class。打字稿中是否自动绑定函数?

我该如何解决这个问题?

您需要bind组件的方法class:

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
        />
   );
}