英文:
How to assign non-string dynamic attributes to a nested component in Svelte?
问题
在另一个组件中正确嵌套具有动态非字符串属性(例如数字和数组)的Svelte组件的语法如下所示:
<script lang="ts">
import MySimpleComponent from './MySimpleComponent.svelte';
let index: number = 1;
let paragraphs: string[] = [
'Nisi ab nesciunt sapiente. Et nostrum quo qui quia non.',
'Aut vel quia vel ducimus eius perferendis.'
];
</script>
<MySimpleComponent {index} {paragraphs} />
以上是正确的语法,将动态属性直接传递给子组件,而无需使用{ }
语法。
英文:
For a Svelte component with dynamic attributes which are not strings (i.e. a number and array), for example MySimpleComponent.svelte
:
<script lang="ts">
export let index : number;
export let paragraphs: string[];
</script>
<h3> { index } </h3>
{#each paragraphs as paragraph, i}
<p> { paragraph } </p>
{/each}
What is the correct syntax to place that component in a different component, and specify those attributes inline? I am trying this, but it doesn't work:
<script lang="ts">
import MySimpleComponent from './MySimpleComponent.svelte';
</script>
<MySimpleComponent
index = { 1 },
paragraphs = {[
'Nisi ab nesciunt sapiente. Et nostrum quo qui quia non.',
'Aut vel quia vel ducimus eius perferendis.'
]},
/>
The error is TS 2322: Type 'string' is not assignable to type 'number'
(or to type string[]
). I assume because the { }
syntax is implicitly expecting a string inside, meaning { 1 }
is really '1'
, not 1
.
What is the correct way to do this? Thanks.
答案1
得分: 2
The problem should be commas, props are separated only by whitespace:
<MySimpleComponent
index={1}
paragraphs={[
'Nisi ab nesciunt sapiente. Et nostrum quo qui quia non.',
'Aut vel quia vel ducimus eius perferendis.'
]} />
(Whitespace in/around the braces and next to the =
should not matter.)
Curly braces pass values verbatim without any conversion. To pass strings one would use quotes around the values with other text or invoke .toString()
manually (e.g. index="1"
).
Note that if a property only contains a {...}
expression it will not be converted to a string but again passed verbatim (see this issue for examples).
英文:
The problem should be commas, props are separated only by whitespace:
<MySimpleComponent
index={1}
paragraphs={[
'Nisi ab nesciunt sapiente. Et nostrum quo qui quia non.',
'Aut vel quia vel ducimus eius perferendis.'
]} />
(Whitespace in/around the braces and next to the =
should not matter.)
Curly braces pass values verbatim without any conversion. To pass strings one would use quotes around the values with other text or invoke .toString()
manually (e.g. index="1"
).
Note that if a property only contains a {...}
expression it will not be converted to a string but again passed verbatim (see this issue for examples).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论