如何从 Svelte 中已经存在的具有相同 css 的标签中删除 Css class?

How to remove Css class from a tag with the same css already present in Svelte?

首先,如果这个问题没有多大意义,我深表歉意。发现很难正确地提出问题,但这就是我正在尝试做的。

当前行为 可以在两个h1标签之间切换cssclass,但启用切换后无法切换;意思是无法删除 h1 标签上的 css class,其中 css class 已经启用。

预期行为 单击同一个活动 h1,它应该删除 css class。

Link到REPL,下面也是同样的代码。

应用程序

<script>
    import Component2 from './Component2.svelte'
    let numbers = [1,2];
    let selectedOption;
    const runThis = (i) => {
        selectedOption = i;
    }
</script>

{#each numbers as number}
    <Component2 isSelected={selectedOption === number} {number} on:click={()=>runThis(number)}/>
{/each}

Component.svelte

<script>
    export let number;
    export let isSelected;
</script>

<h1 on:click class:red={isSelected}>Hello {number}</h1>

<style>
    .red{
        color: red;
    }
</style>

找到答案

App.svelte

<script>
    import Component from './Component.svelte'
    let numbers = [1,2];
    let selectedOption;
    const runThis = (i) => {
        if(selectedOption===i)
            selectedOption=-1
        else
           selectedOption = i;
    }
</script>

{#each numbers as number}
    <Component isSelected={selectedOption === number} {number} on:click={()=>runThis(number)}/>
{/each}

Component.svelte

//same

切换的问题是您必须确保新选择的号码不是已经选择的号码。所以如果当前的selectedOptioni一样,就设置成null:

const runThis = (i) => {
    selectedOption = i !== selectedOption ? i : null;
}

参见REPL