代码之家  ›  专栏  ›  技术社区  ›  Kent Wood

NativeWind将className转换为数组形式的样式,它可以是一个单独的样式对象吗

  •  1
  • Kent Wood  · 技术社区  · 1 年前

    我两者都用 NativeWind twrnc 在我的项目中。
    假设我有一个组件看起来像这样。

    import tw from "twrnc";
    ...
    const Test=(props)=>
    {
      console.log(props);
      return <View style={tw.style(`border`,props.style)}>
        <Text>hello</Text>
      </View>
    }
    

    当我尝试像这样使用这个组件时

    <Test className="bg-red-400 text-red-400" />
    

    它会打印出这样的道具: style: [{backgroundColor: '#f87171'},{color: '#f87171'}] NativeWind将类名转换为样式,但转换为数组。
    然后 tw.style 会弹出一个错误,上面写着 TypeError: str.trim is not a function (it is undefined) 是否可以要求NativeWind不将类名转换为样式数组,而是将其转换为单个样式对象?
    例如 style: {backgroundColor: '#f87171', color: '#f87171'}

    2 回复  |  直到 1 年前
        1
  •  1
  •   Kiran Raj R    1 年前

    在您的项目中,当同时使用NativeWind和twrnc时,当这些样式被传递到tw.style时,NativeWind将类名转换为样式数组可能会导致问题。若要解决此问题,可以手动将样式数组合并到单个对象中,然后再将其传递给tw.style。

    import React from 'react';
    import { View, Text } from 'react-native';
    import tw from 'twrnc';
    import { StyleSheet } from 'react-native';
    
    const mergeStyles = (styles) => {
      if (Array.isArray(styles)) {
        return styles.reduce((acc, style) => ({ ...acc, ...style }), {});
      }
      return styles;
    };
    
    const Test = (props) => {
      const mergedStyle = mergeStyles(props.style);
      return (
        <View style={tw.style(`border`, mergedStyle)}>
          <Text>hello</Text>
        </View>
      );
    };
    
    export default Test;
    
    
    1. mergeStyles function:此函数检查 styles 道具是一个数组。如果是,则将数组元素合并为一个对象。如果它已经是一个对象,它将按原样返回对象。
    2. mergedStyle variable:此变量保存从 合并样式 作用
    3. 经过 mergedStyle tw.style 这个 mergedStyle 然后传递给 tw.样式 以确保其正确工作而不会导致任何错误。

    <Test className="bg-red-400 text-red-400" /> 测试一下,它将正确地合并到一个对象中。

    检查一下,它会起作用的。

        2
  •  0
  •   Kent Wood    1 年前

    我所做的是编写这样一个mergeStyle函数

    import { style } from "twrnc";
    export const mergeStyle = (...args: any[]) => {
        let _args = Array.from(args).reduceRight((res, arg) => {
            if (Array.isArray(arg)) {
                res.push(...arg);
            }
            else {
                res.push(arg);
            }
            return res
        }, []);
        return style(..._args)
    }
    

    然后像这样在测试组件中使用它

    const Test = (props) => {
      return (
        <View style={mergeStyle(`border`, props.style)}>
          <Text>hello</Text>
        </View>
      );
    };