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

虽然这很容易做到,但我无法用TypeScript 2解决如何让<CustomText />拥有<Text />中的所有props ,而不必重新声明它们.

以下是我的组件:

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接口扩展到TextProperties:

interface Props extends TextProperties {
    children?: any
}

编辑

您需要先导入它:

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

React-native相关问答推荐

错误:HostBody::get for prop NativeUnimoduleProxy中出现异常- Android虚拟设备(AVD)使用Expo测试React Native App时崩溃

如何重复使用expo 音频对象S录音?

'无法解析模块.安装react-native-pager-view后的实用程序/平台

使用动画标记时如何优化react 本机 map 性能

如何在react native 中将选定的自定义复选框数据发送到下一页?

React Native - ScrollView 中的 ListView 分页?

React Native 开发中的/ios/index/DataStore文件夹是什么

异步(async)/等待(await)和递归

以编程方式在 React Native 中添加组件

请求的体验使用 Expo SDK v(null),但此 Expo Client至少需要 v23.0.0版本

React Native with Typescript and Jest 在 0.57 更新后被 destruct :Couldn't find preset "module:metro-react-native-babel-preset" relative to directory

在本react-native中具有异步和等待的箭头函数

React Native Negative shadowOffset 创建顶部阴影

如何在 Text 中围绕 Text 包裹 TouchableOpacity?

是否需要使用 StyleSheet.create?

如何将样式传递给 React-Native 中的容器组件

react-native平面列表初始滚动到底部

React Native Navigation 组件路由问题

移动应用程序不需要 CORS?

如何在 React Native 中强制禁用 iOS 暗模式