如何在 svelte 中更新上下文?

How to update context in svelte?

getContext 和setContext 函数只能在组件初始化期间调用。有没有什么方法可以在运行时更新上下文值,例如单击事件。 想象一下,我们将主题或本地化存储在上下文值中,并希望创建一个按钮来更改它。有可能吗? 我试过使用变量设置上下文并更新该变量,但它没有用。像这样:

//App.svelte
<script>
    import {setContext} from 'svelte';
    import Name from './components/Name.svelte';
    let name = 'John';
    setContext('name',name);
    function changeName(){
        /// how to update context here ?
        name = 'Mike'; // Doesn't work!!!
        // setContext('name',name);// Doesn't work - Errors
    }
</script>
<Name></Name>
<button on:click={changeName}>Change Name</button>
//Name.svelte
<script>
    import {getContext} from 'svelte';
    let name = getContext('name');
</script>

<h1> My name is: {name}</h1>

使用 store:

//App.svelte
<script>
    import {setContext} from 'svelte';
    import {writable} from 'svelte/store';
    import Name from './components/Name.svelte';

    let name = writable('John');
    setContext('name',name);

    function changeName(){
        $name = 'Mike';
    }
</script>
<Name></Name>
<button on:click={changeName}>Change Name</button>
//Name.svelte
<script>
    import {getContext} from 'svelte';
    let name = getContext('name');
</script>

<h1> My name is: {$name}</h1>

演示:https://svelte.dev/repl/432d3449cd9b4e5d99a303fa143b3dbc?version=3.6.7