React-Native中动态样式最高效的方式是什么?

36
在React-Native中,您可以使用Stylesheet创建类似css的样式表。使用stylesheet.create而不是纯js对象的主要原因是提高性能。但是,您经常需要动态地为组件设置样式,通常基于它们的props。我基本上发现了三种方法来实现这一点: 以下示例请注意:const styles ...声明在组件外部,因为这是一种常见模式,您可能希望在不同的组件之间共享样式。将省略号以下内容视为render函数的一部分。
  1. Using an array of styles:

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

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

  3. Using a function to create the stylesheet:

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

我想知道在性能方面哪种方法最好,或者是否有其他更高效的方法? 我认为选项2和3根本行不通,因为在属性更改时动态创建新样式表会破坏样式表的整个目的。 关于这个问题,我很乐意听取任何想法或提示!


你找到答案了吗? - FaisalAhmed
很遗憾,大多数情况下我只使用方法1。 - Christoph Göttert
我也认为选项二和三需要时间,而且会使你的代码比通常快五倍增长,所以我建议使用选项一,因为它简单、干净,而且容易写1000次! - Kalinaki M Brandon
这是一个有关React Native中不同样式选项的有趣话题:https://medium.com/@alexeytsuts/choosing-the-technology-for-styles-in-react-native-104ef242bac7 - Christoph Göttert
5个回答

4
在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,
     })
})

同时,您也可以使用任何数据类型进行条件样式设置


2

其中一种方法

// homeSreen
<View style={styles.filterButton(isSelected)}>
  <Text> Strawberry </Text>
</View>

// styles.js
import { StyleSheet } from 'react-native';
import { Colors } from '../../theme';

export default StyleSheet.create({
  container: {
    backgroundColor: Colors.lighter,
  },

  filterButton: isSelected => ({
   padding: 15,
   backgroundColor: isSelected? Colors.background.primary: Colors.background.secondary
  }),
});


0

这样一个复杂的库能够提供最佳性能是难以想象的。当然,它可以提供最佳的开发者体验,但这不是问题的关键。 - Slbox

0
你可以使用React hooks来进行样式表的记忆化,但首先需要进行一些性能检查,以确定样式表的创建是否确实是一个值得优化的CPU和/或内存负担。
以下是一个示例:
const styles = (color) => StyleSheet.create({
    viewStyle: {
        backgroundColor:'red',
        color: color
        }
    })

/*
even though makeStyle is defined in EVERY render,
React will only run it ONCE for any given props.color distinct value.
The resulting value `styles` survives re-renders
*/

const makeStyle = () => styles(props.color)
const styles = useMemo(makeStyle, [props.color]);

这里是官方文档


当前的 StyleSheet.create 实现非常快,而 useMemo 也还可以。问题在于,是否值得使用记忆化(对于非纯子组件),或者每次渲染都创建新对象。 - Stanislav Mayorov

-1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接