在Tailwind CSS/NativeWind中实现可变宽度。

huangapple go评论54阅读模式
英文:

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&#39;s utility classes.

```javascript
    &lt;View className=&#39;w-full h-10 bg-blue-500&#39;&gt;
        &lt;View className={`w-[${percentage}] h-10 bg-blue-300`}/&gt; // this uses back ticks, which works for px values, but not percentage
    &lt;View/&gt;

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.

huangapple
  • 本文由 发表于 2023年2月7日 01:11:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75364475.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定