React UI(即我的应用程序的呈现)与检查元素中显示的内容不一致

React UI (ie. rendering of my app) not consistent with what's shown in inspect element

这里有奇怪的问题。我有一个看起来像这样的进度条:

1 export default function PercentageBar(props) {
2     return (
3         <div className="w-full h-1 my-1 bg-stone-200">
4             <div className={`h-1 bg-orange-500 w-[${props.percent}%]`} />
5         </div>
6     );
7 }

样式是通过 Tailwind CSS 完成的。如果你不熟悉,基本上发生的事情是外部 div 与 parent div 一样宽,高度为 1,顶部和底部的边距为 1,并且是以 gray-ish 色调着色。内部 div 然后在它上面渲染,它的高度也为 1。内部 div 是橙色的,和 props.percent 一样宽(全宽的百分比parent div).

我已确认 props.percent 已正确传递。

props.percent 在运行时动态变化时,特别是第 4 行有时会表现得很奇怪(无论传入的百分比如何)。

例如,如果 props.percent 等于 48,现在等于 52,Inspect Element 告诉我该行是

<div className={`h-1 bg-orange-500 w-[52%]`} />

这是正确的。然而,它呈现如下(一个完整的条)

<div className={`h-1 bg-orange-500 w-[100%]`} />

此外,有时它呈现为 props.percent 等于 0。这仅在 props.percent 更改值后发生。

我尝试过硬刷新、重置缓存等,但问题偶尔会在不同的浏览器中持续存在。如果我足够刷新,有时问题不会出现。知道这里发生了什么吗?非常感谢!

我有同样的类似问题,但是使用 classNames 来解决这个问题,我已经从我使用 component 的地方发送了 classNames,这确保了 component re-render 当道具改变时,我也发送了 ! important 关键字是什么改变了你的 class。希望这能解决您的问题。

export default function PercentageBar({witdhPercentage}) {
    return (
        <div className="w-full h-1 my-1 bg-stone-200">
            <div className={`h-1 bg-orange-500 ${witdhPercentage}`} />
        </div>
    );
}
<PercentageBar witdhPercentage={`!${w-[${props.percent}%]}`} />

如果您使用的是 Tailwind 3(或 JIT 模式下的 Tailwind 2),则无法动态创建 类,因为它们不会包含在最终 CSS.

对于您的变量值,您可以考虑使用 style 道具来设置宽度。例如:

<div style={{width: `${props.percent}%`}} className={'h-1 bg-orange-500'} />

找到答案了!感谢 Ed Lucas 为我指明了正确的方向。他是对的 - 您无法在 Tailwind 中动态创建 class 名称。你可以在here.

上找到解释

但是,使用 Ed 建议的样式标签对我不起作用。相反,我所做的是我创建了一个包含 switch 语句的新函数,该语句 returns 完整的字符串 class 每个宽度值的名称。也就是说:

function getWidthClassName(percent) {
    switch (percent) {
        case 0:
            return 'w-[0%]';
        case 1:
            return 'w-[1%]';
        case 2:
            return 'w-[2%]';
        ...
        case 99:
            return 'w-[99%]';
        case 100:
            return 'w-[100%]';
        default:
            return 'w-[0%]';
    }
}

然后,我的进度条是这样的:

export default function PercentageBar({percent}) {
    let widthClassName = getWidthClassName(percent);
    return (
        <div className="w-full h-1 my-1 bg-stone-200">
            <div className={`h-1 bg-orange-500 ${widthClassName}`} />
        </div>
    );

之所以可行,是因为我们现在不是在运行时动态构造 class 名称,而是静态构造它们。 Tailwind 很开心,我们也很开心。