gpt4 book ai didi

typescript :onPress 类型

转载 作者:行者123 更新时间:2023-12-03 17:50:19 27 4
gpt4 key购买 nike

我刚刚将我的 react-native 项目移植到 typescript 并且有一个关于函数作为 Prop 的问题

我通过:

<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 prop 是哪种类型

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

非常感谢!

最佳答案

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

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

或者

type Props {
onPress(): void
}

或者

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

关于 typescript :onPress 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59901680/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com