【问题标题】:How to extend a native's component's props TypeScript interface in a stateless, functional component in React Native?如何在 React Native 的无状态功能组件中扩展原生组件的 props TypeScript 接口?
【发布时间】:2017-03-10 19:02:50
【问题描述】:

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

虽然这很容易做到,但我无法使用 TypeScript 2 让 <CustomText /> 拥有来自 <Text /> 的所有道具,而无需重新声明它们。

这是我的组件:

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


interface Props {
    children?: any
}

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

如果我尝试将它与&lt;CustomText numberOfLines={1} /&gt; 一起使用,则会导致错误

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 接口中利用它。

【问题讨论】:

    标签: reactjs typescript react-native


    【解决方案1】:

    你只需要让你的Props接口扩展TextProperties

    interface Props extends TextProperties {
        children?: any
    }
    

    编辑

    你需要先导入:

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

    【讨论】:

    • 我试过了,但是 TS2304: Cannot find name 'TextProperties' 出错了。甚至尝试添加&lt;reference path /&gt; 无济于事:(
    • 检查我修改后的答案
    • 试试import { TextProps } from 'react-native' 而不是TextProperties
    猜你喜欢
    • 2016-04-17
    • 2019-10-06
    • 1970-01-01
    • 2020-10-13
    • 2017-04-06
    • 2018-03-24
    • 2023-04-04
    • 2017-11-17
    • 2019-09-16
    相关资源
    最近更新 更多