在此练习中,在 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...
<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:
<PackageInfo {...pkg} />
相反,在
PackageInfo.svelte
中,你可以使用 rest 属性获取一个包含传递到组件中的所有 props 的对象...¥[!NOTE] Conversely, in
PackageInfo.svelte
you can get an object containing all the props that were passed into a component using a rest property...let { name, ...stuff } = $props();
...或者完全跳过 destructuring:
¥...or by skipping destructuring altogether:
let stuff = $props();
...在这种情况下,你可以通过其对象路径访问属性:
¥...in which case you can access the properties by their object paths:
console.log(stuff.name, stuff.version, stuff.description, stuff.website);
<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}
/>