作者:旧日旧面 | 来源:互联网 | 2022-12-08 17:59
在React-Native中,您可以使用样式表来创建类似CSS的样式表。使用styleshee.create
纯js对象的主要原因是提高了性能。但是,您可能经常想根据组件的属性动态设置组件的样式。我基本上发现了执行此操作的三种方法:
请注意以下示例:考虑const styles ...
在Component外部声明,因为它是一种通用模式,您可能希望在不同的Components之间共享样式。将树点下方的所有内容都视为渲染功能的一部分。
使用样式数组:
const styles = StyleSheet.create({viewStyle: {backgroundColor:'red'}})
...
return
使用Stylesheet.flatten:
const styles = StyleSheet.create({viewStyle: {backgroundColor:'red'}})
...
const flattenedStyle = StyleSheet.flatten(styles.viewStyle, {{color: this.props.color}})
return
使用函数创建样式表:
const styles = (color) => StyleSheet.create({
viewStyle: {
backgroundColor:'red',
color: color
}
})
...
const style = styles(this.props.color).viewStyle
return
我想知道哪种方法最适合性能,或者是否还有另一种更高效的方法?我认为选项2和3根本没有用,因为在prop-changes上动态创建新样式表会破坏样式表的整个目的。我很高兴对此主题有任何想法或提示!