StyleSheet.flatten

63 阅读2分钟
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    /**
     * StyleSheet.flatten
     * 该方法可以将多个样式对象合并成一个样式对象。
     * 该方法可以将多个样式对象合并成一个样式对象,并将样式对象中包含的样式属性值合并成一个样式属性值。
     */


     /*
     功能: 1.把各种形式的 style(对象 / 数字ID / 数组,以及里面的 null | undefined | false)解析并合并成一个纯对象
     */

     /*
      合并解析规则:
        数组从左到右合并,后者覆盖前者(同名键后者生效)。

           1. null / undefined / false 会被忽略。

           2. 数字 ID(StyleSheet.create 返回的注册样式)会被解析成对象再参与合并。

           3. 浅合并:嵌套对象(如 shadowOffset)是整体替换,不会“按键合并”。

           4. 例:先有 {shadowOffset:{width:2,height:2}},后面给 {shadowOffset:{width:4}} → 结果只有 {width:4},height 会丢(因为后者整体覆盖前者)。

           5. 数组属性不做深合并(如 transform 是数组):后出现的整个 transform 覆盖前者;想拼接得你自己手动 concat。
     */



     /*案例:

        1.读取“最终样式值”
        const base = { paddingTop: 8, paddingBottom: 8 }
        const override = condition ? { paddingBottom: 24 } : null
        const finalStyle = StyleSheet.flatten([base, override])
        console.log(finalStyle.paddingBottom) // 24 或 8
        2.解析注册样式(数字ID)
     
            const styles = StyleSheet.create({
          box: { padding: 12, backgroundColor: '#eee' },
        })
        const s = StyleSheet.flatten(styles.box)
        // s => { padding: 12, backgroundColor: '#eee' }
        3) 忽略“假值”
        StyleSheet.flatten([{ padding: 8 }, false && { padding: 20 }, null])
        // => { padding: 8 }

        4.嵌套对象整体覆盖
          StyleSheet.flatten([
        { shadowOffset: { width: 2, height: 2 } },
        { shadowOffset: { width: 4 } }, // 覆盖成 {width:4},height 不会保留
      ])

        5.transform 覆盖而非拼接
        StyleSheet.flatten([
        { transform: [{ scale: 1.1 }, { translateY: 10 }] },
        { transform: [{ rotate: '45deg' }] }, // 覆盖了上一整组
      ])
      // 想保留就自己合并 transform 数组



      最终:
          适用场景: 
            需要读取最终样式数值去做计算(比如根据最终 bottomPadding 决定 SafeArea 占位、测量高度等)。
            做一次性**“合成样式对象”**传递到只接受对象的 API(少数库或平台定制场景)。
     */
  </script>
</body>
</html>