在此练习中,在 App.svelte
中,我们忘记传递 PackageInfo.svelte
所需的 name
prop,这意味着 <code>
元素为空并且 npm 链接已损坏。
¥In this exercise, in App.svelte
we’ve forgotten to pass the name
prop expected by PackageInfo.svelte
, meaning the <code>
element is empty and the npm link is broken.
我们可以通过添加 prop 来修复它...
¥We could fix it by adding the prop...
App
<PackageInfo
name={pkg.name}
version={pkg.version}
description={pkg.description}
website={pkg.website}
/>
...但由于 pkg
的属性对应于组件的预期 props,我们可以将它们 ‘spread’ 到组件上:
¥...but since the properties of pkg
correspond to the component’s expected props, we can ‘spread’ them onto the component instead:
App
<PackageInfo {...pkg} />
相反,在
PackageInfo.svelte
中,你可以使用 rest 属性获取一个包含所有传入组件的 props 的对象……
> let { name, ...stuff } = $props();
> ```
>
> ...或者完全跳过 [destructuring](https://web.nodejs.cn/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment):
>
>
```js
> let stuff = $props();
> ```
>
> ...在这种情况下,你可以通过其对象路径访问属性:
>
>
```js
> console.log(stuff.name, stuff.version, stuff.description, stuff.website);
> ```
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<script>
import PackageInfo from './PackageInfo.svelte';
const pkg = {
name: 'svelte',
version: 5,
description: 'blazing fast',
website: 'https://svelte.dev'
};
</script>
<PackageInfo
version={pkg.version}
description={pkg.description}
website={pkg.website}
/>