首页 > 解决方案 > 如何在 Svelte 的类属性中使用反应函数?

问题描述

如何根据 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, 2or -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

标签: javascriptsveltesvelte-3sveltekit

解决方案


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

循环基于#each生成元素sentence,但此变量永远不会更新,因此它永远不会重新渲染。

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

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


推荐阅读