如何使用多种自定义样式设置nativewind元素的样式

问题描述 投票:0回答:3

我想使用我自己的具有某些属性的自定义 className 来设置组件的样式。 Tailwind 允许您通过 App.css 执行此操作,但在 React Native 应用程序中没有。如何将具有某些属性的“.title”类添加到 tailwind 中?

.title {
    font-size: 24px
    font-weight: 800
}

将其应用到 Text JSX 对象:

<Text className="title">Title Text!</Text>
react-native tailwind-css styling
3个回答
0
投票

我想出了这种为多个相同组件设计样式的方法。 Nativewind 和 Tailwind 建议不要使用此方法,但它对两者都有效。

在 tailwind.config.js 文件中,在 module.exports 上方添加以下代码行:

const plugin = require("tailwindcss/plugin");

module.exports = {...}

然后在你的插件列表中添加:

plugin(function ({ addComponents }) {
        addComponents({
            ".title": {
                fontWeight: 800,
                fontSize: 24,
            },
        });
    }),

确保您的样式使用与react-native相同的属性名称,而不是css(fontWeight与font-weight)。重新启动服务器,它应该可以工作了!


0
投票

非常有用。感谢作者。其中一些已在我的几个开源项目中使用,并获得了 400 颗星。希望大家多多鼓励我。

nextjs全栈:https://github.com/huanghanzhilian/c-shopping

react Native(世博)应用程序:https://github.com/huanghanzhilian/c-shopping-rn


-2
投票

您可以使用

twrnc
npm 包来实现此目的。从这里安装它。

在顶部的文件中像这样导入。

import tw from "twrnc";

然后像这样使用它

<Text style={tw` text-2xl font-extrabold`}>Title Text!</Text>
© www.soinside.com 2019 - 2024. All rights reserved.