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

Chr*_*ert 9 performance styles dynamic stylesheet react-native

在React-Native中,您可以使用样式表来创建类似CSS的样式表。使用styleshee.create纯js对象的主要原因是提高了性能。但是,您可能经常想根据组件的属性动态设置组件的样式。我基本上发现了执行此操作的三种方法:

请注意以下示例:考虑const styles ...在Component外部声明,因为它是一种通用模式,您可能希望在不同的Components之间共享样式。将树点下方的所有内容都视为渲染功能的一部分。

  1. 使用样式数组:

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

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

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

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

我想知道哪种方法最适合性能,或者是否还有另一种更高效的方法?我认为选项2和3根本没有用,因为在prop-changes上动态创建新样式表会破坏样式表的整个目的。我很高兴对此主题有任何想法或提示!

Tud*_*soi 0

您可以使用 React hook 来记忆样式表创建,但首先您需要进行一些性能检查,以确定样式表创建实际上是否需要优化 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]);

Run Code Online (Sandbox Code Playgroud)

这是官方文档