![](/img/trans.png)
[英]Why does naming an interface 'Props' not give correct type-checking with a functional component? (typescript & react-native)
[英]How to extend a native's component's props TypeScript interface in a stateless, functional component in React Native?
為了保持一致的樣式,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>
);
如果我嘗試將其與<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';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.