苗条3:子组件的道具和数组
我计划根据出色的 redblobgames 文章,用Svelte 3 / Sapper编写六角形棋盘游戏。
我的问题是关于儿童道具通过父母与父母之间的交流。我以前曾在使用商店的Svelte的较早版本中进行过此操作,但我想没有它也可以做到这一点。
假设我有一块hexagons SVG瓷砖。 Eachtile的形式为:
<script>
// 3D coordinate system, see: http://redblobgames.org for details
export let hex = { q:0, r:0, s: 0 }
export let center = { x:0, y: 0 }
export let corners = []
export let selected = false
let points = corners.map (c => `${c.x.toFixed(0)},${c.y.toFixed(0)}`).join (' ')
// changed by selection process (colors...)
let inner_class = "inner_tile"
const toggle_select = () => {
selected = !selected
}
</script>
<g class="tile" on:click="[ () => toggle_select() }"
<polygon class={ inner_class} [ points } />
<!-- more sophisticated things -->
<!-- sprites, lbels, masks and animations -->
</g>
编辑器组件负责从我的redblobgames六角形处理库的自定义实现中选择布局,设置SVG容器,并使用图块填充网格。 Tis只是每个调用Hex组件的语句:
<svg
xmlns="www.w3.org/2000/svg"
viewBox="-50 -50 589 949"
width="420"
height="500"
>
<!-- just a debugging purpose rectagle ! -->
<rect x="0" y="0" width="400" height="500" style="fill: none; stroke: black;"/>
<g class="tiles">
{#each tiles as tile }
<Hex {...tile} />
{/each}
</g>
</svg>
<!-- this helping zone keeps empty, sadly, whatever I attempt to do -->
<textarea cols="50" rows="10">
{ selected_tiles_output }
</textarea>
当试图在木板下方的四面体中显示选定的图块参考(q,r,s)时出现问题。不要在脚本中执行此操作:
// imports...
let tiles = []
let selected_tiles = new Set ()
let selected_tiles_output = ''
// onMount to assemlble the board ...
// reactive part which doesn't work:
$: selected_tiles_ouptut = tiles
.filter (tile => tile.selected)
.map (tile => tile.hex)
.map (h => `q: ${h.q}, r: ${h.r}, s: ${h.s} \n`)
.reduce ((acc, val) => acc + val, '')
问题:
父容器是否有可能在子组件数组中观察某种道具(也称为“选定”),这是子组件中的一种“可弯曲”道具?
我最终应该考虑使用商店来代替吗?
注意:在开发的这一点上,由于变化很大,我很难共享一些完整的工作代码示例或源代码。在最坏的情况下,我可以压缩并通过邮件发送src / routes和src / components sapper的文件夹!
有人能让我按正确的方向前进吗?
致谢,
答案 0 :(得分:2)
您可以使用bind:
指令让父母从孩子那里接收反应性更新-请参阅文档here
在将图块传递到十六进制时,您似乎可以将其绑定,如下所示:
{#each tiles as {hex, center, corners, selected} }
<Hex {hex} {center} {corners} bind:selected />
{/each}
然后在Editor.svelte
中更改tile.selected
时Hex.svelte
应该会得到更新。
或者,您可以在父toggle_select
中而不是在Editor
中定义Hex
,并将其作为对Hex
的支持。这样,对图块的更新就直接在Editor
中发生:
<!-- Editor.svelte -->
<g class="tiles">
{#each tiles as tile }
<Hex {...tile} toggle_select={() => tile.selected = !tile.selected} />
{/each}
</g>
<!-- Hex.svelte -->
<script>
export let toggle_select
希望有帮助!