简体   繁体   English

在React Native中基于父组件传递样式

[英]Passing Styles Based on Parent Component in React Native

I have a <Text> component that is being passed a style so.. 我有一个正在传递样式的<Text>组件。

TextFile.js : TextFile.js

<Text style={styles.text}> 
  This is a line of text and this might be a second line 
</Text>

screenFile.js : screenFile.js

<View style={styles.viewContainer}>
    <TextFile style={styles.textWithinContainer}>
</View>

textFiles/styles.js : textFiles/styles.js

text: {
    fontSize: 20,
    color: 'black',
    fontWeight: '400',
}

screenFiles/styles.js : screenFiles/styles.js

textWithinContainer: {
    textAlign: 'center',
}

textAlign within textWithInContainer is not being applied. 未使用textWithInContainer textAlign 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 . 如果我在styles.text添加textAlign: 'center'给我我想要的样式,但是它在不同的屏幕中使用,并且我只希望它在screenFile I want the styles from styles.textWithinContainer to override the styles in styles.text . 我想从样式styles.textWithinContainer覆盖样式styles.text How would I go about this? 我将如何处理?

You aren't delegating the styles you pass to TextFile to the actual Text element in TextFile . 你是不是委托传递给样式TextFile的实际Text的元素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>

From the React Native documentation : 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. 您还可以传递样式数组-数组中的最后一个样式具有优先级,因此您可以使用它来继承样式。

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 . 因此,如果在textWithContainer传递textAlign ,它将被应用在Text组件中,并且可以根据需要重用, 而无需 textAlign

In my initial TextFile, I passed style as an argument, and in the styles array, just used style as the second item in the array. 在我最初的TextFile中,我将style作为参数传递,并且在styles数组中,仅将style用作数组中的第二项。

const TextFile = ({ text, style }) => (
   <Text style=([styles.text, style])> {text} </Text>
);

Whenever TextFile gets used, it will apply any styles being given within that component, and/or default to the initial styles it's being given in styles.text . 每当使用TextFile时,它将应用该组件中给出的任何样式,和/或默认应用于在styles.text中给出的初始样式。

Thank you @Li357! 谢谢@ Li357!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM