【发布时间】:2019-01-11 11:24:33
【问题描述】:
在 React-Native 中,您可以使用 Stylesheet 创建类似 css 的样式表。使用 styleshee.create 来支持普通 js-objects 的主要原因是提高了性能。但是,您通常可能希望动态地设置组件的样式,通常基于它们的 props。我基本上找到了三种方法:
以下示例的注意事项: 考虑在组件外部声明 const styles ...,因为它是一种常见模式,您可能希望在不同组件之间共享样式.将树点下方的所有内容视为渲染函数的一部分。
-
使用样式数组:
const styles = StyleSheet.create({viewStyle: {backgroundColor:'red'}}) ... return <View style={[styles.viewStyle, {color: this.props.color}]} /> -
使用 Stylesheet.flatten:
const styles = StyleSheet.create({viewStyle: {backgroundColor:'red'}}) ... const flattenedStyle = StyleSheet.flatten(styles.viewStyle, {{color: this.props.color}}) return <View style={flattenedStyle} /> -
使用函数创建样式表:
const styles = (color) => StyleSheet.create({ viewStyle: { backgroundColor:'red', color: color } }) ... const style = styles(this.props.color).viewStyle return <View style={style} />
我想知道哪种方法在性能方面最好,或者是否还有另一种性能更高的方法?我认为选项 2 和 3 根本不可能,因为在 prop-changes 上动态创建新样式表破坏了样式表的全部目的。对于这个主题的任何想法或提示,我都很高兴!
【问题讨论】:
-
你找到答案了吗?
-
很遗憾没有。在大多数情况下,我只使用方法 1。
-
我也认为选项 2 和 3 会花费时间,并且会使您的代码比平时快 5 倍,因此我建议使用选项 1,因为它简单、干净且易于编写 1000 次!
标签: performance react-native dynamic styles stylesheet