在 React Native 中基于父组件传递样式 [英] Passing Styles Based on Parent Component in React Native
问题描述
我有一个
组件正在传递一个样式,所以..
I have a <Text>
component that is being passed a style so..
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',
}
textWithInContainer
中的
textAlign
没有被应用.如果我将 textAlign: 'center'
添加到 styles.text
给了我我想要的样式,但它被用于不同的屏幕,我只希望它在 中居中屏幕文件
.我希望 styles.textWithinContainer
中的样式覆盖 styles.text
中的样式.我该怎么办?
textAlign
within textWithInContainer
is not being applied. If I add textAlign: 'center'
to styles.text
gives me the style I want but it's being used in different screens and I only want it centered in the screenFile
. I want the styles from styles.textWithinContainer
to override the styles in styles.text
. How would I go about this?
推荐答案
您没有将传递给 TextFile
的样式委托给 Text
中的实际 元素>文本文件代码>.你可以做的是通过传递一个样式对象的数组来应用它:
You aren't delegating the styles you pass to TextFile
to the actual Text
element in TextFile
. What you can do is add the styles together by passing an array of style objects to apply it:
<Text style={[styles.text, props.style]}>
This is a line of text and this might be a second line
</Text>
来自 React Native 文档:
你也可以传递一个样式数组——数组中的最后一个样式具有优先权,因此你可以使用它来继承样式.
You can also pass an array of styles - the last style in the array has precedence, so you can use this to inherit styles.
因此,如果您在 textWithContainer
中传递 textAlign
,它将被应用到 Text
组件中,并且可以像您一样重复使用希望没有 textAlign
.
Thus, if you pass textAlign
in textWithContainer
, it'll be applied in the Text
component, and it can be reused as you wish without textAlign
.
这篇关于在 React Native 中基于父组件传递样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!