Svelte - {#each} {/each} 在传递给组件的对象中生成唯一的 ID

Svelte - {#each} {/each} generating unique ids in an object passed down to component

我想生成一个自定义组件列表,由一个输入字段和几个复选框组成:

<script>
const messages = [
 { id: "2fzae4", text: "aaaaa"},
 { id: "456ndr", text: "bbbbb"}

];

const tags = [
  { id: "01", label: "Twitter"},
  { id: "02", label: "Instagram"}
];
</script>

<ul>
{#each messages as msg (msg.id)}
  <li>
      <Ainput textField={msg.text} {tags}/>
  </li>
{/each}
</ul>

// This is a part of the <Ainput> component 

<div class="wrapper">
  <input type="text" bind:value={textField}/>
  <Tag {tags} />
</div>
// Tag component, a set of checkboxes
<script>
 export let tags;
</script>

<div>
 {#each tags as tag (tag.id)}
 <div>
   <checkbox id="{tags.id}"/>
   <label for="{tags.id}">{tags.label}</label>
 </div>
 {/each}
</div>

我需要在每次迭代时在数组 'tags' 中传递唯一的 tag.id 值以使复选框起作用,但如何实现呢?

你不需要那样做。查看 this answer here。你可以把<input> 放在里面<label>,这样就不需要id/for了:

<div>
 {#each tags as tag (tag.id)}
   <div>
     <label>
      <input type="checkbox"/>
      {tags.label}
     </label>
   </div>
 {/each}
</div>

工作演示:

<div>
  <label>
    <input type="checkbox">
    Click me, please!
  </label>
</div>
<div>
  <label>
    <input type="checkbox">
    No, click me instead!
  </label>
</div>