这看起来很奇怪,但是这里有一个似乎对我有用的东西(使用@Ali SabziNezhad的suggestion)。它允许共享文本属性(例如color
)和对齐方式(在这种特定情况下为center
)
function Component() {
return (
<CenterText style={{color: 'red'}}>
Centered <Text style={{fontSize: 50}}>text</Text>
</CenterText>
);
}
export function CenterText({children, ...otherProps}: Text['props']) {
return (
<Text {...otherProps}>
<View
style={{flexDirection: 'row', alignItems: 'center'}}
children={children}
/>
</Text>
);
}
我们甚至可以拥有一个更通用的对齐文本组件:
export function AlignedText({children, alignItems, ...otherProps}: AlignedTextProps) {
return (
<Text {...otherProps}>
<View
style={{flexDirection: 'row', alignItems: alignItems}}
children={children}
/>
</Text>
);
}
type Alignment = 'baseline' | 'center' | 'flex-end' | 'flex-start' | 'stretch';
type AlignedTextProps = Text['props'] & {alignItems: Alignment};
我们可以使用这个来定义CenterText
:
export function CenterText(props: TextProps) {
return <AlignedText alignItems='center' {...props} />;
}
或直接为:
function Component() {
return (
<AlignedText style={{color: 'red'}} alignItems='center'>
Centered <Text style={{fontSize: 50}}>text</Text>
</AlignedText>
);
}