如何为React Native Web Pressable组件正确添加onHoverIn TS类型



我正在将React Native Web与Typescript结合使用,我想使用库中的React NativeWeb Pressable组件。

然而,当VSCode将React Native Web道具类型(如onHoverIn(归咎于此时,我遇到了一个问题。这种情况下的主要问题是React Native道具类型定义不包含RNWeb 中的增强道具

有人能告诉我如何以正确的方式解决这个问题吗
我不想在我想使用Pressable 的每个文件中禁用TS检查

这是错误消息:

type '{ 
children: Element; 
accessibilityRole: "button"; 
delayLongPress: number; 
disabled: false; 
onHoverIn: () => void; 
onHoverOut: () => void; 
onKeyDown: () => void; 
onLongPress: () => void; 
onPress: () => void; 
onPressIn: () => void; 
onPressOut: () => void; }' is not assignable to type 
'IntrinsicAttributes & PressableProps & RefAttributes<View>'.
Property 'onHoverIn' does not exist on type
'IntrinsicAttributes & PressableProps & RefAttributes<View>'.ts(2322)

代码示例:

import React from 'react';
import {
Text, Button, ScrollView, StyleSheet, View, Pressable 
} from 'react-native'; // in webpack conf I have an alias that fetches data from the React Native Web
....
<Pressable
accessibilityRole="button"
delayLongPress={750}
disabled={false}
onHoverIn={() => {
console.log('onHoverIn');
}}
onHoverOut={() => {
console.log('onHoverOut');
}}
>
<Text>Pressable</Text>
</Pressable>

谢谢你的帮助!

我只用了一个";不错";方法它只是创建一个组件包装,重新导出原始的Pressable,但包含增强的道具。

我不确定这是";最好的一个";解决方案,因为我们必须物理地创建一些React组件作为包装器,但我们的问题与仅类型有关

工作示例:

// This file is mainly for extending the basic Pressable RN props type
// by the React Native Web-specific properties to avoid TS blaming
import * as React from 'react';
import {
Pressable as RNWebPressable,
PressableProps as RNWebPressableProps
} from 'react-native';
export type PressableProps = RNWebPressableProps & {
// RNWeb properties
onHoverIn: (e: MouseEvent) => void;
onHoverOut: (e: MouseEvent) => void;
}
export function Pressable(props: PressableProps) {
return (
<RNWebPressable {...props} />
);
}

最新更新