我正在逐漸將 RN 專案轉移到 typescript。我有一個關于為作為道具傳遞給組件的樣式宣告型別的問題。
組件內的 Props 定義如下:
interface Props {
children: ReactNode;
style?: ViewStyle;
}
如果我只傳遞一個簡單的樣式物件就可以了,例如:
<Component style={{ marginTop: 1 }}>...children...</Component>
<Component style={styleObj}>....children...</Component>
但如果我傳遞一組樣式,它會失敗:
<Component style={[styleObj, { marginTop: someVar }]}>...children...</Component>
指定樣式道具型別的最佳方法是什么?
編輯:TS訊息是:
TS2559: Type '({ flex: number; } | { marginTop: number; })[]' has no properties in common with type 'ViewStyle'. Component.tsx(12, 3): The expected type comes from property 'style' which is declared here on type 'IntrinsicAttributes & Props'
uj5u.com熱心網友回復:
如果您可以控制stylepropType,請將其更改為:
interface Props {
children: ReactNode;
style?: StyleProp<ViewStyle>;
}
進一步討論
有時,當我發現自己重用了基礎組件的 props 時,我喜歡用基礎組件的 props 型別擴展 prop 型別,以省去自己必須弄清楚自己需要什么型別的麻煩。
例子
這不是最詳盡的示例,但它應該展示此模式的主要目的。我希望你發現這個有用。
我有一個名為 的自定義組件CustomView,它的核心只是一個react-native View組件。然后我可以用 的 擴展CustomView的道具型別View。
interface Props extends React.ComponentProps<typeof View> {
customPropsOne: string;
// also contains all props of the View component
}
const CustomView = (props: Props) => {
// make use of the ...rest operator to extract the extended View props
const {customPropsOne, ...rest} = props;
return(
<View {...rest}>
{customPropsOne}
</View>
)
}
// example component usage
<CustomView
style={[myStyles, anotherStyle]}
accessibilityLabel={"main view"}>
{children}
</CustomView>
uj5u.com熱心網友回復:
TypeScript 已經有一個style型別:
React.CSSProperties
uj5u.com熱心網友回復:
將陣列傳遞給style不起作用。它需要一個型別為 的物件ViewStyle。您可以使用展開語法構造這個由多個樣式物件組成的物件。
<Component style={{ ...styleObj, ...{ marginTop: someVar }}}></Component>
甚至更短
<Component style={{ ...styleObj, marginTop: someVar }}></Component>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/521701.html
標籤:打字稿反应式
