我有一个<Text>
组件正在传递一个样式,所以..
TextFile.js
:
<Text style={styles.text}>
This is a line of text and this might be a second line
</Text>
screenFile.js
:
<View style={styles.viewContainer}>
<TextFile style={styles.textWithinContainer}>
</View>
textFiles/styles.js
:
text: {
fontSize: 20,
color: 'black',
fontWeight: '400',
}
screenFiles/styles.js
:
textWithinContainer: {
textAlign: 'center',
}
textAlign
内的textWithInContainer
未被适用。如果我将textAlign: 'center'
添加到styles.text
给我我想要的风格,但它在不同的屏幕中使用,我只希望它在screenFile
中心。我希望styles.textWithinContainer
的样式覆盖styles.text
中的样式。我该怎么做?
您没有将传递给TextFile
的样式委托给Text
中的实际TextFile
元素。你可以做的是通过传递样式对象数组来将样式添加到一起来应用它:
<Text style={[styles.text, props.style]}>
This is a line of text and this might be a second line
</Text>
来自the React Native documentation:
您还可以传递一组样式 - 数组中的最后一个样式具有优先权,因此您可以使用它来继承样式。
因此,如果你在textAlign
中传递textWithContainer
,它将被应用在Text
组件中,并且可以在没有textAlign
的情况下重复使用。
在我最初的TextFile中,我将style
作为参数传递,并且在styles
数组中,仅使用style
作为数组中的第二项。
const TextFile = ({ text, style }) => (
<Text style=([styles.text, style])> {text} </Text>
);
每当使用TextFile
时,它将应用在该组件中给出的任何样式,和/或默认为它在styles.text
中给出的初始样式。
谢谢@Li357!