Fre*_*nge 10 typescript react-native
我刚刚将我的 react-native 项目移植到 typescript 并且有一个关于函数作为道具的问题
我通过:
<DisplayCardsWithLikes
data={testData}
likes={500}
onPress={() => this.props.navigation.navigate("CardDetailScreen")}
/>
Run Code Online (Sandbox Code Playgroud)
到
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>
);
};
Run Code Online (Sandbox Code Playgroud)
错误:
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<...>'
Run Code Online (Sandbox Code Playgroud)
总结: onPress 作为道具传递(是一个函数)。在子类型 onPress:Function 上显示错误(上面的那个),但 onPress:any 有效。我基本上不知道 onPress prop 是哪种类型
所以没什么疯狂的,但是如果我将 onPress 定义为一个函数,它会显示一个错误,所以显然这不是正确的类型。你知道这个 onPress 函数是哪种类型吗?
非常感谢!
Muh*_*har 21
您需要定义类型如下以摆脱 tslint 的类型错误:
type Props {
onPress: (event: GestureResponderEvent) => void
}
Run Code Online (Sandbox Code Playgroud)
或者
type Props {
onPress(): void
}
Run Code Online (Sandbox Code Playgroud)
或者
type Props {
onPress(params: type): void
}
Run Code Online (Sandbox Code Playgroud)
Ale*_*yne 12
该错误消息显示了您的函数将接受的类型,如下所示:
(event: GestureResponderEvent) => void
Run Code Online (Sandbox Code Playgroud)
需要注意的是,=> void这意味着它需要一个不返回值的函数。
但是这个函数:
() => this.props.navigation.navigate("CardDetailScreen")
Run Code Online (Sandbox Code Playgroud)
确实返回一个值。不带 的箭头函数{}返回其表达式的结果。
修复方法是添加{}到您的回调中,以便该函数不会返回任何内容,这将与预期类型匹配:
onPress={() => { this.props.navigation.navigate("CardDetailScreen") } }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7182 次 |
| 最近记录: |