自定义Svelte RadioButton组件bind:group异常:选中时全显checked状态
问题分析与解决
问题出在组件内的选中状态判断逻辑上。你通过bind:group绑定的checked变量存储的是选中单选按钮的value值(而非布尔值),但组件里直接用{#if checked}判断——非空字符串在Svelte中会被视为true,导致选中任意按钮时,两个组件的判断条件都成立,从而同时显示选中图标。
修复步骤
1. 调整RadioButton组件的判断逻辑
将组件内的{#if checked}改为{#if checked === value},只有当绑定的变量值等于当前按钮的value时,才显示选中图标。
2. 修复后的RadioButton.svelte代码
<script> import { toKebabCase } from "$lib/utils.js"; import Icon from "$lib/components/Icon.svelte"; export let checked; export let classNames = ""; export let name = ''; export let value = ''; </script> <label for={toKebabCase(value)} class="relative flex flex-row items-center {classNames}"> <input type="radio" id="{toKebabCase(value)}" name={name} value="{value}" class="flex shrink-0 h-5 w-5 mr-2 appearance-none" bind:group={checked} /> <span class="absolute cursor-pointer"> {#if checked === value} <Icon type="radioButtonChecked" classNames="h-6 w-6 fill-gs-teal" /> {:else} <Icon type="radioButton" classNames="h-6 w-6 fill-white" /> {/if} </span> <slot /> </label>
3. 父组件(+Page.svelte)无需修改
原代码的bind:checked={radioValue}逻辑是正确的,它会将选中按钮的value同步到radioValue变量中,配合组件内的判断逻辑即可实现正确的单选效果。
原理说明
bind:group对单选按钮的作用是:将选中按钮的value值赋值给绑定的变量,而非布尔值。- 组件内必须通过对比绑定变量与当前按钮的
value,才能准确判断该按钮是否处于选中状态。
内容的提问来源于stack exchange,提问作者Filippo
相关产品推荐
相关产品推荐

