我只是将我的react原生项目移植到类型记录中,并有一个关于作为道具的功能的问题。
我路过:
<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作为支柱传递(是一个函数)。在子类型onPress:Function上显示一个错误(上面的错误),onPress:任意工作。我根本不知道onPress道具是哪种类型
所以这并不疯狂,但是如果我将onPress定义为一个函数,它就会显示一个错误,因此显然这不是正确的类型。你知道这个onPress函数是哪种类型的吗?
非常感谢!
发布于 2020-01-24 18:40:36
您需要将类型定义如下,以消除tslint中的类型错误:
type Props {
onPress: (event: GestureResponderEvent) => void
}或
type Props {
onPress(): void
}或
type Props {
onPress(params: type): void
}发布于 2020-01-24 18:38:00
该错误消息显示函数将接受的类型,如下所示:
(event: GestureResponderEvent) => void需要注意的是=> void,这意味着它需要一个不返回值的函数。
但这一职能:
() => this.props.navigation.navigate("CardDetailScreen")返回一个值。箭头函数没有{}的返回它们表达式的结果。
修复方法是将{}添加到回调中,这样函数就不会返回任何内容,这将与预期的类型匹配:
onPress={() => { this.props.navigation.navigate("CardDetailScreen") } }https://stackoverflow.com/questions/59901680
复制相似问题