gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:29:31 24 4
gpt4 key购买 nike

在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}]} />
  • 使用Stylesheet.flatten:
    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/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com