【问题标题】:How to easily get ts type of react-native element prop?如何轻松获取 ts 类型的 react-native element prop?
【发布时间】:2019-01-30 19:00:31
【问题描述】:

我发现自己最近经常关注

// MyButton.tsx
import { TouchableWithoutFeedback } from "react-native"

interface Props {
 onPress: () => void
}

//...

<TouchableWithoutFeedback onPress={this.props.onPress} />

本质上,我正在围绕 react native 组件制作自己的“包装器”组件,这些包装器组件通常采用与它们包装的 react native 组件类似的道具。我必须总是重新输入这些道具。

我不想扩展原生组件的所有属性,而是公开一些非常具体的属性。做这样的事情会很棒

interface Props = {
  onPress: TouchableWithoutFeedback.onPress
}

不幸的是,这不起作用,但是由于我没有定义自己的类型,因此这样的事情对道具安全有很大帮助。

这是否可以通过某种方式实现?

【问题讨论】:

    标签: reactjs typescript react-native


    【解决方案1】:

    您需要使用类型定义,而不是类本身。假设你已经安装了@types/react-native

    import { TouchableWithoutFeedbackProps } from 'react-native'
    
    interface Props {
      onPress: TouchableWithoutFeedbackProps["onPress"] // <-- must be bracket notation
    }
    

    我认为他们所有的组件道具定义都遵循相同的命名模式,所以View 将是ViewPropsText 将是TextProps 等等

    括号表示法是因为点表示法只对 ts 中的命名空间有效

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-22
      • 2018-03-01
      • 2018-08-28
      • 2011-02-09
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      相关资源
      最近更新 更多