面试题答案
一键面试- 创建上下文:
- 在Svelte中,使用
setContext
和getContext
函数来处理上下文。首先从'svelte'
模块中导入setContext
函数。例如,在一个名为contextStore.js
的文件中(这只是一个示例组织方式):
import { setContext } from'svelte'; const contextKey ='my - context - key'; const myContextData = { someValue: 'default value', someFunction: () => { console.log('This is a function in context'); } }; const setMyContext = () => { setContext(contextKey, myContextData); }; export { setMyContext };
- 在Svelte中,使用
- 在祖先组件中提供上下文:
- 在祖先组件(假设名为
Parent.svelte
)中,导入创建上下文的函数并调用它。
<script> import { setMyContext } from './contextStore.js'; setMyContext(); </script> <div> <h1>Parent Component</h1> {#if true} <Child /> {/if} </div>
- 这里的
<Child />
是后代组件,祖先组件通过调用setMyContext
设置了上下文数据,后代组件就可以访问这些数据。
- 在祖先组件(假设名为
- 在后代组件中订阅上下文数据:
- 在后代组件(假设名为
Child.svelte
)中,从'svelte'
模块导入getContext
函数,并使用之前定义的上下文键来获取上下文数据。
<script> import { getContext } from'svelte'; const contextKey ='my - context - key'; const myContext = getContext(contextKey); </script> <div> <h2>Child Component</h2> <p>{myContext.someValue}</p> <button on:click={myContext.someFunction}>Call function from context</button> </div>
- 这样,后代组件就可以通过
getContext
获取祖先组件提供的上下文数据,并使用这些数据进行相应的操作。
- 在后代组件(假设名为