【发布时间】:2021-10-23 19:40:19
【问题描述】:
如何根据svelte中函数的返回值设置元素类属性?
我正在尝试用 svelte 制作快速打字游戏。我需要根据状态(非活动/活动/正确/错误)以不同颜色显示当前键入的字母。
我有一个函数可以从数组sentenceState 中获取输入字母的状态,其中x 是单词索引,y 是字母索引。
function getLetterStyle(x, y) {
const state = sentenceState[x][y];
switch (state) {
case null:
return '';
case 0:
return 'text-black border-l border-black';
case 1:
case 2:
return 'text-green-500';
case -1:
return 'text-red-500';
}
}
sentenceState 是一个反应式数组,其中每个值是null, 0, 1, 2 或-1。
基于这些值,我想动态更改元素的类属性。
我试着像这样使用这个函数:
{#each activeSentence as word, wordIndex}
{#each word as letter, letterIndex}
<span class={getLetterStyle(wordIndex, letterIndex)>{letter}</span>
{/each}
{/each}
这似乎不像我想象的那样工作。它适用于初始页面加载。但是当sentenceState更新时,类并没有相应的改变。
getLetterStyle() 只会被调用一次。有没有办法使用带有类属性参数的函数?我在这里做错了什么?
提前致谢!
编辑:这是一个 REPL https://svelte.dev/repl/4b02dd3eacee43748e05de3071e59f0b?version=3.42.2
【问题讨论】:
-
嘿根 ????您能否提供一个REPL 并提供一个可复制的最小示例?
标签: javascript svelte svelte-3 sveltekit