我刚刚将我的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函数是什么类型的吗?
多谢了!
3条答案
按热度按时间y0u0uwnf1#
你需要如下定义type来摆脱tslint的类型错误:
或
或
c0vxltue2#
该错误消息显示了它将为您的函数接受的类型,如下所示:
值得注意的是
=> void
,这意味着它需要一个不返回值的函数。但是这个功能:
{}
的箭头函数返回其表达式的结果。修复方法是将
{}
添加到回调中,以便函数不返回任何与预期类型匹配的内容:fquxozlt3#
我从React Native导入了GestureResponderEvent,然后将其用作我的事件类型:
这里是onPress代码: