首页 > 解决方案 > React-Native 中动态样式的最高效方式是什么?

问题描述

在 React-Native 中,您可以使用Stylesheet创建类似 css 的样式表。styleshee.create使用纯 js-objects 的主要原因是提高性能。但是,您通常可能希望动态地设置组件的样式,通常基于它们的 props。我基本上找到了三种方法:

以下示例的注意事项:考虑const styles ...在组件之外声明,因为它是一种常见模式,您可能希望在不同组件之间共享样式。将树点下方的所有内容视为渲染函数的一部分。

  1. 使用样式数组:

    const styles = StyleSheet.create({viewStyle: {backgroundColor:'red'}})
    ...
    return <View style={[styles.viewStyle, {color: this.props.color}]} />
    
  2. 使用 Stylesheet.flatten:

    const styles = StyleSheet.create({viewStyle: {backgroundColor:'red'}})
    ...
    const flattenedStyle = StyleSheet.flatten(styles.viewStyle, {{color: this.props.color}})
    return <View style={flattenedStyle} />
    

  3. 使用函数创建样式表:

    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 上动态创建新样式表破坏了样式表的全部目的。我很高兴有任何关于这个主题的想法或提示!

标签: performancereact-nativedynamicstylesstylesheet

解决方案


在这里,您可以为每种样式在 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,
     })
})

您还可以传递任何数据类型以进行条件样式


推荐阅读