我刚刚将react-native 项目移植到typescript,并对作为props 的函数提出了一个问题

我路过:

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

type Props = {
  onPress: Function
}


const FloatingActionBut到nSimple = (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 到 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 到 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定义为一个函数,它会显示一个错误,所以显然这不是正确的类型.你知道这个onPress功能是哪种类型的吗?

谢谢!

推荐答案

您需要按以下方式定义类型,以消除tslint中的类型错误:

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

type Props {
   onPress(): void
}

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

React-native相关问答推荐

如何在Reaction本地日历中 Select 年份?

Google SignIn SDK 因抛出错误而失败,发生不可恢复的登录失败 -catch 错误

错误:看起来您在另一个中嵌套了一个NavigationContainer

如何运行 React-Native 示例?

如何在 React Native 中删除警告

library not found for -lRCTGeolocation

react-native:如何在离线模式下在模拟器上运行应用程序?

React Navigation TabNavigator:在选项卡更改时重置上一个选项卡

我们如何将 Firebase Analytics 与基于 expo 的 react-native 应用程序一起使用

将图标添加到drawer抽屉react-navigation v5

使用 React Native 打开 iOS iPad 模拟器

React-native Xcode 构建失败 -> 'RCTAssert.h file not found'

动画属性启动时 ReactNative ActivityIndi​​cator 不显示 false

如何在 React Native 中使用 index.js 而不是 (index.ios.js, index.android.js) 进行跨平台应用程序?

在 React Native 中,如何使用浅渲染测试我的组件?

如何用 Realm 元素文件组织 React Native?

在 React 中调用 getDerivedStateFromProps 中的方法

JSON 解析错误:无法识别的令牌'<'

无法解析模块react-native-screen

/bin/sh: adb: 找不到命令