面试题答案
一键面试1. 在Child.svelte中通过模块上下文传递数据给Parent.svelte
Child.svelte
<script>
// 使用setContext来传递数据
import { setContext } from 'svelte';
const dataToParent = 'Hello from Child';
setContext('childData', dataToParent);
</script>
{#if false}
<!-- 避免此部分内容渲染,只是为了展示数据传递逻辑 -->
<Parent />
{/if}
解释:在Child.svelte
中,通过import { setContext } from'svelte';
导入setContext
函数,然后使用setContext
将数据dataToParent
以键'childData'
传递出去。这里使用{#if false}
包裹<Parent />
只是为了展示逻辑,实际不会渲染Parent
组件。
Parent.svelte
<script>
import { getContext } from'svelte';
const receivedData = getContext('childData');
</script>
<p>{receivedData}</p>
解释:在Parent.svelte
中,通过import { getContext } from'svelte';
导入getContext
函数,然后使用getContext('childData')
获取Child.svelte
传递过来的数据,并在页面上显示。
2. 在Child.svelte中使用Slot嵌入来自Parent.svelte的自定义内容
Child.svelte
<div>
<slot></slot>
</div>
解释:Child.svelte
中使用<slot>
标签来定义插槽,这样在Parent.svelte
中引入Child.svelte
时,放在<Child>
标签之间的内容会被渲染到这个插槽位置。
Parent.svelte
<Child>
<p>This is custom content from Parent</p>
</Child>
解释:在Parent.svelte
中,在<Child>
标签之间添加自定义内容,这些内容会显示在Child.svelte
的插槽位置。
3. 给Child.svelte的某个DOM元素添加一个简单的Action使其在页面加载时改变背景颜色
Child.svelte
<script>
const changeBgColor = node => {
node.style.backgroundColor = 'lightblue';
return {
destroy() {
node.style.backgroundColor = 'initial';
}
};
};
</script>
<div use:changeBgColor>
<slot></slot>
</div>
解释:首先在Child.svelte
的<script>
部分定义了一个名为changeBgColor
的Action函数。该函数接收一个node
参数,即应用该Action的DOM元素。在函数内部,将元素的背景颜色设置为lightblue
。同时返回一个对象,对象中的destroy
函数在组件销毁时会将背景颜色恢复为初始值。然后在<div>
标签上使用use:changeBgColor
将这个Action应用到该div
元素上,当页面加载时,该div
的背景颜色就会变为lightblue
。