我刚刚将我的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函数的类型是什么吗?
非常感谢!
答案 0 :(得分:8)
您需要按如下所示定义类型,以消除tslint中的类型错误:
type Props {
onPress: (event: GestureResponderEvent) => void
}
OR
type Props {
onPress(): void
}
OR
type Props {
onPress(params: type): void
}
答案 1 :(得分:2)
该错误消息显示了您的函数将接受的类型,如下所示:
(event: GestureResponderEvent) => void
要注意的重要一点是=> void
,这意味着它期望一个不返回值的函数。
但是此功能:
() => this.props.navigation.navigate("CardDetailScreen")
确实返回一个值。没有{}
的箭头函数返回其表达式的结果。
解决方法是将{}
添加到回调中,以便该函数不返回任何与期望的类型匹配的内容:
onPress={() => { this.props.navigation.navigate("CardDetailScreen") } }