MST
星途 面试题库

面试题:Svelte中Props与Context在组件通信状态管理中的基础应用

请简述在Svelte组件通信状态管理中,Props和Context分别适用于什么样的场景,并举例说明如何通过Props和Context在父子组件间传递简单数据。
42.7万 热度难度
前端开发Svelte

知识考点

AI 面试

面试题答案

一键面试

Props适用场景

Props 适用于父子组件间的单向数据传递,即父组件向子组件传递数据。这种方式简单直接,适合传递一些具体的、局部的数据,比如组件的配置项、展示内容等。例如,在一个 Button 组件中,父组件可能会传递按钮的文本、颜色等属性给子组件。

Props传递数据示例

  1. 父组件(App.svelte)
<script>
    let buttonText = '点击我';
    let buttonColor = 'blue';
</script>

<Button text={buttonText} color={buttonColor} />

<script context="module">
    import Button from './Button.svelte';
</script>
  1. 子组件(Button.svelte)
<script>
    export let text;
    export let color;
</script>

<button style="color: {color}">{text}</button>

Context适用场景

Context 适用于在组件树中跨级传递数据,不必在每一层中间组件都手动传递数据。它适合传递一些全局性的数据,比如用户认证信息、主题配置等,多个组件都可能需要用到,但不想在中间层级组件中都声明一遍的情况。

Context传递数据示例

  1. 祖先组件(App.svelte)
<script>
    import { setContext } from'svelte';
    let theme = 'dark';
    setContext('theme', theme);
</script>

<GrandChild />

<script context="module">
    import GrandChild from './GrandChild.svelte';
</script>
  1. 后代组件(GrandChild.svelte)
<script>
    import { getContext } from'svelte';
    let theme = getContext('theme');
</script>

<p>当前主题: {theme}</p>

即使中间有多层组件,GrandChild 组件也能获取到 App 组件设置的 theme 数据,无需在中间组件传递。