reactjs - 如何在 React Native 的无状态功能组件中扩展 native 组件的 props TypeScript 接口(interface)?

标签 reactjs typescript react-native

为了保持一致的样式,React Native 文档建议编写 <CustomText />包装 native 的文本组件 <Text />组件。

虽然这很容易做到,但我无法使用 TypeScript 2 解决如何制作 <CustomText /> 的问题。拥有<Text />的所有 Prop 无需重新声明它们。

这是我的组件:

import React from 'react';
import { Text } from 'react-native';


interface Props {
    children?: any
}

const CustomText: React.SFC<Props> = (props) => (
    <Text {...props}>
        {props.children}
    </Text>
);

如果我尝试将它与 <CustomText numberOfLines={1} /> 一起使用会导致错误

TS2339: Property 'numberOfLines' does not exist on type 'IntrinsicAttributes & Props'

react-native.d.ts ,我看到有这个导出:

export interface TextProperties extends React.Props<TextProperties> {

    /**
     * Specifies should fonts scale to respect Text Size accessibility setting on iOS.
     */
    allowFontScaling?: boolean

    /**
     * Line Break mode. Works only with numberOfLines.
     * clip is working only for iOS
     */
    lineBreakMode?: 'head' | 'middle' | 'tail' | 'clip'

    /**
     * Used to truncate the text with an elipsis after computing the text layout, including line wrapping, such that the total number of lines does not exceed this number.
     */
    numberOfLines?: number

    /**
     * Invoked on mount and layout changes with
     *
     * {nativeEvent: { layout: {x, y, width, height}}}.
     */
    onLayout?: ( event: LayoutChangeEvent ) => void

    /**
     * This function is called on press.
     * Text intrinsically supports press handling with a default highlight state (which can be disabled with suppressHighlighting).
     */
    onPress?: () => void

    /**
     * @see https://facebook.github.io/react-native/docs/text.html#style
     */
    style?: TextStyle

    /**
     * Used to locate this view in end-to-end tests.
     */
    testID?: string
}

但我不确定如何扩展它以在我的组件的 Props 中利用它界面。

最佳答案

你只需要让你的Props接口(interface)扩展TextProperties:

interface Props extends TextProperties {
    children?: any
}

编辑

您需要先导入它:

import { Text, TextProperties } from 'react-native';

关于reactjs - 如何在 React Native 的无状态功能组件中扩展 native 组件的 props TypeScript 接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40295718/

相关文章:

javascript - redux-form 字段参数为空

javascript - 错误: Request failed with status code 401 axios in React JS

javascript - 设计和构建多角色 ReactJS 应用程序

javascript - 根据参数注入(inject)正确的服务

react-native - react 原生拉伸(stretch)行项目?

javascript - 我如何在 React Native 中调用另一个组件的函数?

javascript - 为什么带有 MongoDB 的 Node.js Express 不响应获取 API 调用(ReactJS 和 Redux)?

javascript - 如果 esModuleInterop 为 true 配置 TypeScript 转译,我是否需要显式 allowSyntheticDefaultImports?

mysql - 如何在 Typescript 项目中使用 express-mysql-session?

reactjs - 如何将标题换行到新行 react native