javascript - 如何在 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, 2
or -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
解决方案
没有什么能让你的#each
循环反应。
循环基于#each
生成元素sentence
,但此变量永远不会更新,因此它永远不会重新渲染。
这里的一种解决方案是响应式地计算每个字母的样式,然后让#each
基于此生成元素。
工作 REPL:https ://svelte.dev/repl/77977b39b8964c8ba32acb063ceeb407?version=3.42.2
推荐阅读
- kubernetes-helm - 如何创建一个模板依赖于另一个模板的舵图
- javascript - 如何在 R Shiny 中查询元素
- sql-server - Docker 上的 LocalDb V11.0
- javascript - 在浏览器控制台中为特定单词着色
- r - 计算一起购买的产品
- java - 在困难的场景中有效地保持 Java 集合排序
- javascript - 调用和调用函数之间有区别吗?
- javascript - 如何根据 div 宽度将类应用于 div?
- excel - 当单元格公式结果更改时,如何修复 msgbox 显示两次?
- gstreamer - 如何使用 GStreamer 0.10 将 mp4 filesrc 流式传输到 rtspsink