我必须承认,我还没有完全掌握Svelte的概念。我制作了一个组件,其目的是执行某种API请求。每个按钮组件可以具有两个或更多按钮:
Screenshot of "Button component"
在按钮组组件中单击按钮时,我想执行以下操作:
按钮组件
<div class="buttons-wrapper">
<label>
{labelTitle}
{#if helpText}
<Icon iconType="help" iconSize="small" iconTitle={helpText} />
{/if}
</label>
<div class="buttons">
{#each options as option, index}
<button class={index === 0 ? 'selected' : ''}
value={option.id}
name={option.name}
on:click={setSelected}>
{option.name}
</button>
{/each}
</div>
</div>
父组件
<ButtonGroup options={[{ id: 0, name: 'Option 1' }, { id: 1, name: 'Option 2' }]} labelTitle="Button label" />
在我的示例中,我在点击时调用setSelected,应该从组件本身还是从父组件执行?
我真的在这里迷路了...
答案 0 :(得分:0)
您可以将ButtonGroup设置为受控组件(它通过道具获取其当前值并通知更改),也可以将其设置为 Uncontrol Component (内部存储其自身的状态)。另外,您的组件可以同时支持这两种,例如:
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
export let labelTitle = 'button label';
export let options = []
export let selected = 0
function setSelected(e){
const newValue = Number(e.target.value)
selected = newValue
dispatch('change', {value: newValue})
}
</script>
<style>
button.selected {
background-color: red;
}
</style>
<div class="buttons-wrapper">
<label>
{labelTitle}
</label>
<div class="buttons">
{#each options as option, index}
<button class={selected === index ? 'selected' : ''}
value={option.id}
name={option.name}
on:click={setSelected}>
{option.name}
</button>
{/each}
</div>
</div>
https://svelte.dev/repl/12f5112852bd4dceb382578a4cfeed06?version=3.12.1