面试题答案
一键面试在Svelte组件中,可以在声明props
时为其设置默认值并进行类型检查。对于MyComponent
组件接收message
字符串类型prop
的情况,代码如下:
<script lang="ts">
export let message: string = 'Hello, World!';
</script>
<p>{message}</p>
在上述代码中,通过export let message: string = 'Hello, World!'
声明了一个名为message
的prop
,指定其类型为string
并设置默认值为Hello, World!
。这样在使用MyComponent
组件时,如果没有传递message
,则会使用默认值。同时通过类型声明string
对其类型进行了简单检查。