打字稿:onPress类型

弗雷迪昂格

我刚刚将我的react-native项目移植到了打字稿,并对功能作为道具有疑问

即时通讯:

<DisplayCardsWithLikes
data={testData}
likes={500}
onPress={() => this.props.navigation.navigate("CardDetailScreen")}
/>

type Props = {
  onPress: Function
}


const FloatingActionButtonSimple = (props:Props) => {
  const {onPress} = props
  return (
    <View style={styles.containerFab}>
      <TouchableOpacity style={styles.fab} onPress={onPress}>
        <Icon name="plus" size={16} color={"white"} />
      </TouchableOpacity>
    </View>
  );
};

错误:

Error, caused by child onPress:
o overload matches this call.
  Overload 1 of 2, '(props: Readonly<TouchableOpacityProps>): TouchableOpacity', gave the following error.
    Type 'Function' is not assignable to type '(event: GestureResponderEvent) => void'.
      Type 'Function' provides no match for the signature '(event: GestureResponderEvent): void'.
  Overload 2 of 2, '(props: TouchableOpacityProps, context?: any): TouchableOpacity', gave the following error.
    Type 'Function' is not assignable to type '(event: GestureResponderEvent) => void'.ts(2769)
index.d.ts(5125, 5): The expected type comes from property 'onPress' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<TouchableOpacity> & Readonly<TouchableOpacityProps> & Readonly<...>'
index.d.ts(5125, 5): The expected type comes from property 'onPress' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<TouchableOpacity> & Readonly<TouchableOpacityProps> & Readonly<...>'

简介:onPress作为prop传递(是一个函数)。在子类型上,onPress:Function显示错误(上面的错误),但是onPress:any可以工作。我基本上不知道onPress道具是哪种类型

所以没有什么疯狂的,但是如果我将onPress定义为一个函数,它将显示一个错误,显然这不是正确的类型。您知道此onPress函数的类型是什么?

非常感谢!

穆罕默德·梅哈(Muhammad Mehar)

您需要按如下所示定义类型,以摆脱tslint的类型错误:

type Props {
   onPress: (event: GestureResponderEvent) => void
}

要么

type Props {
   onPress(): void
}

要么

type Props {
   onPress(params: type): void
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章