You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Svelte中点击按钮显示输入框后如何动态聚焦该输入框?

解决Svelte中动态显示输入框并自动聚焦的问题

你的问题核心是:设置edit = true后,Svelte不会立刻更新DOM,此时focusInput还未绑定到实际的输入框元素,导致调用focus()时出现undefined错误。以下是几种可行的解决方案:

方法一:使用svelte/tick等待DOM更新

通过await tick()等待当前DOM更新完成后,再调用聚焦方法:

<script>
    import { tick } from 'svelte';
    let edit = false;
    let focusInput;

    const toggleEdit = async () => {
        edit = true;
        await tick(); // 等待DOM完成更新,确保输入框已挂载
        focusInput.focus();
    }
</script>

<button on:click={toggleEdit}>Edit</button>
{#if edit}
    <input type="text" bind:this={focusInput}>
{/if}

方法二:利用on:render事件触发聚焦

Svelte 3.48及以上版本支持on:render事件,该事件会在元素首次渲染到DOM时触发,刚好适合动态显示的输入框:

<script>
    let edit = false;
    let focusInput;

    const toggleEdit = () => {
        edit = true;
    }

    const handleRender = () => {
        focusInput.focus();
    }
</script>

<button on:click={toggleEdit}>Edit</button>
{#if edit}
    <input type="text" bind:this={focusInput} on:render={handleRender}>
{/if}

方法三:使用反应式语句监听状态变化

通过Svelte的反应式语句$:,监听edit和focusInput的状态变化,满足条件时自动聚焦:

<script>
    let edit = false;
    let focusInput;

    const toggleEdit = () => {
        edit = true;
    }

    // 当edit为true且focusInput存在时,执行聚焦
    $: if (edit && focusInput) {
        focusInput.focus();
    }
</script>

<button on:click={toggleEdit}>Edit</button>
{#if edit}
    <input type="text" bind:this={focusInput}>
{/if}

内容的提问来源于stack exchange,提问作者Lee Morgan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 12:33:28