Svelte 5:循环中传递给子组件的属性如何随$state变化重新计算?
解决Svelte 5中循环内属性不更新的问题
针对你遇到的循环内函数调用属性不随selectedCell变化更新的问题,有几种可行的解决方式:
方法1:将判断逻辑移至子组件内部
修改SubComponent,让它直接接收cell和selectedCell,在内部用$derived计算选中状态:
<!-- SubComponent.svelte --> <script lang="ts"> export let cell: Cell; export let selectedCell: Optional<Cell>; const selected = $derived(cell.equals(selectedCell)); </script> <!-- 子组件原有内容,使用内部的selected变量 -->
父组件只需传递必要参数:
{#each cells as cell} <SubComponent {cell} {selectedCell}/> {/each}
方法2:在父组件中创建派生状态数组
通过$derived生成一个与cells对应的选中状态数组,循环时直接取用对应索引的值:
<script lang="ts"> let selectedCell: Optional<Cell> = $state(undefined); const cells = [new Cell(1), new Cell(2)]; // 派生每个cell的选中状态 const cellSelections = $derived( cells.map(cell => cell.equals(selectedCell)) ); </script> {#each cells as cell, i} <SubComponent selected={cellSelections[i]}/> {/each}
方法3:用响应式函数包装判断逻辑
在父组件中定义一个依赖selectedCell的函数,模板中调用该函数:
<script lang="ts"> let selectedCell: Optional<Cell> = $state(undefined); const cells = [new Cell(1), new Cell(2)]; function isSelected(cell: Cell) { return cell.equals(selectedCell); } </script> {#each cells as cell} <SubComponent selected={isSelected(cell)}/> {/each}
由于函数内部引用了$state声明的selectedCell,Svelte会自动追踪其变化,每次selectedCell更新时都会重新执行函数并更新属性值。
内容的提问来源于stack exchange,提问作者h345k34cr
相关产品推荐
相关产品推荐

