如何在 Svelte 的 class 属性中使用反应函数?

How can I use a reactive function inside a class attribute in Svelte?

如何根据 svelte 中函数的 return 值设置元素 class 属性?

我正在尝试用 svelte 制作一款快速打字游戏。我需要根据状态 (inactive/active/right/wrong) 以不同颜色显示当前键入的字母。

我有一个函数可以从数组 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。 基于这些值,我想动态更改元素的 class 属性。 我试着像这样使用这个功能:

{#each activeSentence as word, wordIndex}
    {#each word as letter, letterIndex}
      <span class={getLetterStyle(wordIndex, letterIndex)>{letter}</span>
    {/each}
{/each}

这似乎不像我想象的那样有效。它适用于初始页面加载。但是当 sentenceState 更新时, class 不会相应地改变。

getLetterStyle()只会调用一次。有没有办法使用带有 class 属性参数的函数?我在这里做错了什么?

提前致谢!

编辑:这是一个 REPL https://svelte.dev/repl/4b02dd3eacee43748e05de3071e59f0b?version=3.42.2

没有什么能让你的 #each 循环反应。

#each 循环正在根据 sentence 生成元素,但此变量永远不会更新,因此它永远不会重新呈现。

这里的一个解决方案是响应式地计算每个字母的样式,然后让 #each 基于此生成元素。

工作 REPL:https://svelte.dev/repl/77977b39b8964c8ba32acb063ceeb407?version=3.42.2