如何专注于 Svelte 中新增的输入? [英] How to focus on newly added inputs in Svelte?
本文介绍了如何专注于 Svelte 中新增的输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 #each 来显示 tasks
数组的每个成员的输入.当我单击添加任务"按钮时,一个新元素被插入到数组中,因此 #each 循环中会出现一个新输入.
I use #each to display an input for every member of the tasks
array. When I click the Add task button, a new element is inserted into the array, so a new input appears in the #each loop.
如何聚焦在单击添加任务"按钮时添加的输入?
How do I focus the input that's been added upon clicking the Add task button?
<script>
let tasks = [];
function addTask() {
tasks = [...tasks, { title: "" }];
}
</script>
{#each tasks as task}
<input type="text" bind:value={task.title} />
{/each}
<button on:click={addTask}>Add task</button>
推荐答案
Rich Harris 有更好的解决方案
您可以使用use:action
:
动作是在创建元素时调用的函数.
Actions are functions that are called when an element is created.
例如:
<script>
let tasks = [];
function addTask() {
tasks = [...tasks, { title: "" }];
}
function init(el){
el.focus()
}
</script>
{#each tasks as task}
<input type="text" bind:value={task.title} use:init />
{/each}
<button on:click={addTask}>Add task</button>
这篇关于如何专注于 Svelte 中新增的输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文