简体   繁体   English

Svelte:从 element prop 应用顺风 class

[英]Svelte: Applying tailwind class from element prop

This works:这有效:

let players = [
    { id: 1, name: 'Player 1', color: 'amber' },
    { id: 2, name: 'Player 2', color: 'sky' },
];
...
<span class="underline decoration-{player.color}-500">{player.name}</span>

Only sometimes.只有某些时候。 I can see the prop is applied to the class properly in the resulting HTML when inspecting the page source in the browser:在浏览器中检查页面源时,我可以看到该道具在生成的 HTML 中正确应用于 class :

but the color is not applied to the underline most of the time.但大多数时候颜色不会应用于下划线。 When I change the source HTML to a static color, save the file, and then change it back, one or both of the underlines stops working.当我将源 HTML 更改为 static 颜色时,保存文件,然后将其改回,一个或两个下划线停止工作。 Similarly, when I change a color in the javascript, usually the other color starts working, but not all of the time.同样,当我更改 javascript 中的一种颜色时,通常另一种颜色会开始工作,但并非总是如此。 Is this due to a race condition?这是由于比赛条件吗? Am I using Svelte wrong which might explain this seemingly random behaviour?我是否使用错误的 Svelte 可以解释这种看似随机的行为?

I think there is a mistake in the template string.我认为模板字符串有错误。 This should be the correct one.这应该是正确的。

<span class={`underline decoration-${player.color}-500`}>{player.name}</span>

From this : 从此

Tailwind doesn't include any sort of client-side runtime, so class names need to be statically extractable at build-time, and can't depend on any sort of arbitrary dynamic values that change on the client. Tailwind 不包括任何类型的客户端运行时,因此 class 名称需要在构建时静态提取,并且不能依赖于客户端上更改的任何类型的任意动态值。 Use inline styles for these situations, or combine Tailwind with a CSS-in-JS library like Emotion if it makes sense for your project.在这些情况下使用内联 styles,或者如果对您的项目有意义,则将 Tailwind 与 Emotion 等 CSS-in-JS 库结合使用。

What you should do:你应该做什么:

<script>
let players = [
    { id: 1, name: 'Player 1', className: 'decoration-amber-500' },
    { id: 2, name: 'Player 2', className: 'decoration-sky-500' },
];
</script>

<span class="underline {player.className}">{player.name}</span>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM