Ale*_*old 1 svelte svelte-component svelte-3
我不知道为什么这个不更新。我对 Svelte 比较陌生,但我知道使用 thing = thing 方法强制更新对象数组。
不过,我不确定为什么这不会重新渲染?我首先将其作为矩阵,我认为可能有一些嵌套破坏了它,但现在这实际上只是一个平面数组。它在点击时更新矩阵,但不触发重新渲染。
<script>
import Nested from './Nested.svelte';
let matrix = new Array(9).fill(null)
let turn = 0
let handleChange = (index) => {
if (matrix[index] != null) return
let newColor = turn % 2 == 0 ? 'red' : 'blue'
matrix[index]= newColor
turn++
matrix = matrix
}
</script>
{#each matrix as team, index}
<Nested team={team} index={index} click={handleChange}/>
{#if (index==2 || index==5)}
<br />
{/if}
{/each}
Run Code Online (Sandbox Code Playgroud)
嵌套组件:
<script>
export let index;
export let click;
export let team;
let color = 'white';
if (team) color = team;
</script>
<style>
div {
width: 100px;
height: 100px;
border: 1px solid black;
display: inline-block;
margin: 0;
}
</style>
<div style="background-color: {color}" on:click={(e)=>click(index)}>
{color}
</div>
Run Code Online (Sandbox Code Playgroud)
使用 Svelte 时,需要记住的重要一点是script块中的代码仅在创建组件时执行。
在您的情况下,这意味着该行if (team) color = team;仅运行一次(在实例化时),之后不再运行。
如果您希望重新执行某些操作,则必须使用以下命令将其声明为反应式$:
对你来说这将成为
$: if (team) color = team
Run Code Online (Sandbox Code Playgroud)
每当使用的任何变量(团队和颜色)发生变化时,都会重新执行此操作。
请注意,您还可以简单地将变量标记为响应式(Svelte为您注入let )
export let index;
export let click;
export let team;
$: color = team ?? 'white'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2091 次 |
| 最近记录: |