【问题标题】:Typescript: _this2.onClick is not a function打字稿:_this2.onClick 不是函数
【发布时间】:2018-08-14 15:57:51
【问题描述】:

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

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

_this2.onClick 不是函数。 (在'_this2.onClick()'中,'_this2.onClick'是未定义的)

我认为这是因为onClick() 函数未绑定到组件类。 typescript 中的函数是否自动绑定?

我该如何解决这个问题?

【问题讨论】:

    标签: javascript typescript react-native typescript2.0 native-base


    【解决方案1】:

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

    【讨论】:

    • 这很奇怪。不需要this.onClick.bind(this)。相反this._renderRow.bind(this) 解决了问题!谢谢。
    • 是的,我会的。请修复this.onClick()。
    • 不,只有this.onClick 而不是this.onClick()
    猜你喜欢
    • 1970-01-01
    • 2019-11-22
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    • 2019-02-21
    • 2017-02-10
    • 2023-03-03
    • 1970-01-01
    相关资源
    最近更新 更多