英文:
What's the difference of using `array` vs `StyleSheet.compose()` in React Native
问题
// 与标题相符:
这些用法有什么区别?从用户界面的角度看,它们似乎执行相同的功能。
import { StyleSheet, View } from 'react-native';
import type { JSX } from 'react';
const App = (): JSX.Element => (
<View>
<View style={[styles.viewA, styles.viewB]} />
<View style={StyleSheet.compose(styles.viewA, styles.viewB)} />
</View>
);
const styles = StyleSheet.create({
viewA: {
width: 100,
height: 100,
color: '#f00',
},
viewB: {
color: '#0f0',
},
});
英文:
As per title:
What's the difference of these usages? I can see they all performing the same from UI perspective
import { StyleSheet, View } from 'react-native'
import type { JSX } from 'react'
const App = (): JSX.Element => (
<View>
<View style={[styles.viewA, styles.viewB]} />
<View style={StyleSheet.compose(styles.viewA, styles.viewB)} />
</View>
)
const styles = StyleSheet.create({
viewA: {
width: 100,
height: 100,
color: '#f00'
},
viewB: {
color: '#0f0'
}
})
答案1
得分: 1
从您的示例中,使用两者都是相同的,因为样式是静态的。compose
在样式是动态的时候非常有用。请参见以下官方描述:
Stylsheet.compose(style1, style2)
结合了两种样式,使得 style2
会覆盖 style1
中的任何样式。如果其中一个样式为假值(falsy),则返回另一个样式,而不会分配数组,节省了内存分配,并保持了 PureComponent
检查中的引用相等性。
参考链接:react-native/Libraries/StyleSheet/StyleSheet.js
英文:
From your example, using both are same since styles are static. compose
is useful when styles are dynamic. See the official description below
Stylsheet.compose(style1, style2)
combines two styles such that style2
will override any styles in style1
. If either style is falsy, the other one is returned without allocating an array, saving allocations and maintaining reference equality for PureComponent checks
compose<T: DangerouslyImpreciseStyleProp>(
style1: ?T,
style2: ?T,
): ?T | $ReadOnlyArray<T> {
if (style1 != null && style2 != null) {
return ([style1, style2]: $ReadOnlyArray<T>);
} else {
return style1 != null ? style1 : style2;
}
},
Reference : react-native/Libraries/StyleSheet/StyleSheet.js
答案2
得分: 0
我认为在一段时间内,StyleSheet.compose
可能性能更高。我认为StyleSheet.create
返回的对象曾经经历了某种类型的优化。在提交记录中,将 StyleSheet.create
更改为身份函数时,他们说它将不再返回一个数字。所以在发生这个变化之前,除非在底层发生了一些魔法,否则我认为你不能在不使用该函数的情况下合并样式。
自从这个变化发生后,StyleSheet.flatten
和 StyleSheet.compose
似乎已经过时。除了进行样式预处理之外,StyleSheet
整体似乎已经过时。
我认为它仍然在使用的原因是出于传统/惯例。
英文:
I think there was a time when StyleSheet.compose
would have been more performant. I think the object returned by StyleSheet.create
used to go through some type of optimization. In the commit where StyleSheet.create
is changed to be an identity function, they say it will no longer return a number. So before that change occurred, unless there was some magic going on under the hood, I dont think you could merge styles without using that function.
Since the change, StyleSheet.flatten
and StyleSheet.compose
seem obsolete. Outside of doing style preprocessing, StyleSheet
as a whole seem obsolete.
I think the reason it remains in use is out of tradition/convention.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论