英文:
Implementing a variable width in Tailwind CSS/NativeWind
问题
我正在尝试使用变量来创建一个进度条,通过使用两个视图并将其宽度设置为父视图的百分比。我希望使用Tailwind的实用类来实现这一目标。
```javascript
<View className='w-full h-10 bg-blue-500'>
<View className={`w-[${percentage}] h-10 bg-blue-300`}/> // 这里使用反引号,它适用于像px值这样的情况,但不适用于百分比
<View/>
我尝试在className
中的各个位置添加百分号,但没有成功。显然,如果我使用style
属性,它可以工作,但理想情况下我只想使用className
属性。
<details>
<summary>英文:</summary>
I am trying to use a variable to create a progress bar by using two views and setting the width equal to a percentage of the parent view. I would like to do this using Tailwind's utility classes.
```javascript
<View className='w-full h-10 bg-blue-500'>
<View className={`w-[${percentage}] h-10 bg-blue-300`}/> // this uses back ticks, which works for px values, but not percentage
<View/>
I have tried adding % sign everywhere in the className
, with no success. Obviously, it works if I use the style
attribute, but ideally I would only use the className
attribute.
答案1
得分: 3
如前所述,Tailwind 不会在运行时生成类。要使用类来实现这一点,要么需要Tailwind生成每个可能的百分比类(只有当percentage
是整数时才可行),但这会使样式变得臃肿,或者需要在运行时不断扫描每个元素以查找类似于Tailwind的类。
最佳选择,特别是因为您正在执行如此简单的操作,是使用style
属性。
英文:
As mentioned, Tailwind does not generate classes at runtime. To achieve this with classes either requires Tailwind to make every single possible class that's a percentage (only feasible if percentage
is an integer), but that bloats your styles, or for there to be something at runtime, constantly scanning each element for tailwind-like classes.
The best option, especially since you're doing such a simple property, is to use the style
attribute.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论