代码之家  ›  专栏  ›  技术社区  ›  Velidan

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

  •  0
  • Velidan  · 技术社区  · 3 年前

    我将React Native Web与Typescript结合使用,我想使用 React Native Web Pressable 来自库的组件。

    然而,当VSCode指责React原生Web道具类型时,我遇到了一个问题,比如 昂霍温 。这种情况下的主要问题是,React原生道具类型定义不包含 增强 RNWeb的道具

    有人能给我一个建议,告诉我如何用正确的方法解决这个问题吗?
    我不想禁用TS签入每个我想使用Pressable的文件

    以下是错误消息:

    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>
    

    谢谢你的帮助!

    0 回复  |  直到 3 年前
        1
  •  1
  •   Velidan    3 年前

    我只用一种“不错”的方法解决了这个问题。它只是创建一个组件包装器,重新导出原始的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} />
      );
    }
    
    推荐文章