面试题答案
一键面试Props适用场景
Props 适用于父子组件间的单向数据传递,即父组件向子组件传递数据。这种方式简单直接,适合传递一些具体的、局部的数据,比如组件的配置项、展示内容等。例如,在一个 Button
组件中,父组件可能会传递按钮的文本、颜色等属性给子组件。
Props传递数据示例
- 父组件(App.svelte)
<script>
let buttonText = '点击我';
let buttonColor = 'blue';
</script>
<Button text={buttonText} color={buttonColor} />
<script context="module">
import Button from './Button.svelte';
</script>
- 子组件(Button.svelte)
<script>
export let text;
export let color;
</script>
<button style="color: {color}">{text}</button>
Context适用场景
Context 适用于在组件树中跨级传递数据,不必在每一层中间组件都手动传递数据。它适合传递一些全局性的数据,比如用户认证信息、主题配置等,多个组件都可能需要用到,但不想在中间层级组件中都声明一遍的情况。
Context传递数据示例
- 祖先组件(App.svelte)
<script>
import { setContext } from'svelte';
let theme = 'dark';
setContext('theme', theme);
</script>
<GrandChild />
<script context="module">
import GrandChild from './GrandChild.svelte';
</script>
- 后代组件(GrandChild.svelte)
<script>
import { getContext } from'svelte';
let theme = getContext('theme');
</script>
<p>当前主题: {theme}</p>
即使中间有多层组件,GrandChild
组件也能获取到 App
组件设置的 theme
数据,无需在中间组件传递。