performance - React-Native 中动态样式的最高效方式是什么?
问题描述
在 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 上动态创建新样式表破坏了样式表的全部目的。我很高兴有任何关于这个主题的想法或提示!
解决方案
在这里,您可以为每种样式在 react native 中进行动态样式。
像这样
<Text style={styles.simpleText('red')}>Required field</Text>
// In styling
const styles = StyleSheet.create({
simpleText: (colorProp = 'black') => ({ // default black set
fontSize: 14,
color: colorProp,
})
})
您还可以传递任何数据类型以进行条件样式
推荐阅读
- java - 无法获取“https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/4.0.1/gradle-4.0.1.pom”
- reactjs - 检查作为参数传递的现有数组项的数组
- vb.net - 将 VB 网络中的数据插入 Postgresql
- go - 恐慌()堆栈跟踪不显示函数参数
- git - Git 使用 rebase 重写历史
- python - Python Selenium 访问内部元素
- java - Removing lock on non-graceful application shutdown
- python - How to make my bullets fire when I press my key?
- php - Laravel - 测试。如何修复错误 Symfony\Component\HttpKernel\Exception\NotFoundHttpException
- r - R - 不能从
我有一个从普通数据帧生成的数据帧向量列表,如下所示。基因表达包含标识每个观察的细胞系、基因、染色体区域和表达水平的列——多个基因可能属于特定的染色体区域,我想将一个染色体区域的表达与其他所有基因进行比较。它看起来像这样:
gene region cell_line