简体   繁体   中英

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:

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. Similarly, when I change a color in the javascript, usually the other color starts working, but not all of the time. Is this due to a race condition? Am I using Svelte wrong which might explain this seemingly random behaviour?

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. Use inline styles for these situations, or combine Tailwind with a CSS-in-JS library like Emotion if it makes sense for your project.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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