Svelte:以可重复使用的方式关联标签和输入 [英] Svelte: Associate label and input in a reusabe way

查看:32
本文介绍了Svelte:以可重复使用的方式关联标签和输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个 Svelte 输入组件,它应该可以在同一页面上多次使用.

<label>{label}</label><div><输入绑定:值><!-- 还有一些元素-->

尝试关联标签和输入我有以下问题:

  • 我无法通过将外部

    更改为 来使用隐式关联,因为输入不是直接子级.
  • 我不能使用标签 for 属性,因为重复使用该元素会创建可变的相同 ID.

有没有办法在 Svelte 中创建组件实例唯一 ID(前缀或后缀),或者是否有其他解决方案可以解决此问题.


或者是手动设置一个随机字符串作为 id 的最佳解决方案?

<div><label for={id}>{label}</label><div><输入{id}绑定:值><!-- 还有一些元素-->

解决方案

你可以在模块上下文中定义一个计数器,然后用它来创建唯一的 ID

输入.svelte

<脚本>出口让标签让价值让 eltId = 'input_'+ counter++<div><label for={eltId}>{label}</label><div><input id={eltId} bind:value>

App.svelte

<输入标签='选择国家/地区'/><输入标签='选择国家/地区'/><输入标签='选择国家/地区'/>

参见 REPL

I'm building a Svelte input component which should be usable multible times on the same page.

<div>
    <label>{label}</label>
    <div>
        <input bind:value>
        <!-- some more elements -->
    </div>
</div>

Trying to associate label and input I have the following problem:

Is there a way to create component instance unique ids (pre- or postfixed) in Svelte or is there another solution to this problem.


Or is the best solution to manually set a random string as id?

<script>
    const id = random_string();
    /* ... */
</script>

<div>
    <label for={id}>{label}</label>
    <div>
        <input {id} bind:value>
        <!-- some more elements -->
    </div>
</div>

解决方案

You could define a counter in module context and then use it to create unique IDs

Input.svelte

<script context="module">
    let counter = 0
</script>
<script>
        export let label
        let value
        let eltId = 'input_'+ counter++
</script>

<div>
    <label for={eltId}>{label}</label>
    <div>
        <input id={eltId} bind:value>
    </div>
</div>    

App.svelte

<script>
    import Input from './Input.svelte'
</script>

<Input label='Select Country' />
<Input label='Select Country' />
<Input label='Select Country' />

See REPL

这篇关于Svelte:以可重复使用的方式关联标签和输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆