在React-Native中,您可以使用Stylesheet创建类似CSS的样式表。使用styleshee.create
代替纯js对象的主要原因是提高了性能。但是,您可能经常想根据组件的属性动态设置组件的样式。我基本上发现了这样做的三种方法:
请注意以下示例:考虑将const styles ...
声明在Component之外,因为它是一种常见模式,您可能希望在不同的Components之间共享样式。将树点下方的所有内容都视为渲染功能的一部分。
const styles = StyleSheet.create({viewStyle: {backgroundColor:'red'}})
...
return <View style={[styles.viewStyle, {color: this.props.color}]} />
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上动态创建新样式表会破坏样式表的整个目的。我很高兴对此主题有任何想法或提示!
最佳答案
您是否考虑过JS库(例如Styled components
)中的CSS?
您可以传递 Prop 并获得动态风格,请注意:
https://styled-components.com/docs/basics#passed-props
关于performance - React-Native中动态样式的最高性能方式是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51674797/