简体   繁体   English

(苗条)如何从组件访问以前的组件道具

[英](svelte) how can I access previus component props from component

how can I access a prop from a same-named component in the same container?如何从同一个容器中的同名组件访问道具?

<Container>
 <Line x={10} y={12}>
 <Line x={14} y={8}>
 <Line x={50} y={30}>
</Container>

so the second <Line> get these props (x, y)所以第二个<Line>得到这些道具 (x, y)
but also the previous Line props (without that user need to specify it)还有以前的 Line 道具(无需该用户指定)

so in the second Line Case, it get the 14 and 8, but needs to get also 10, and 12所以在第二行案例中,它得到 14 和 8,但还需要得到 10 和 12

in the line.svelte :line.svelte

<script>
  export let x;
  export let y;
</script>

<div style="top: {x}px; left: {y}px;" />

I need to get the previous x, y because I need to do some calculation and find the angle and connect the 2 lines (and I know the formula).我需要得到之前的 x, y 因为我需要做一些计算并找到角度并连接 2 条线(我知道公式)。

My idea is something like document.querySelector("Line")[thisComponetIndex - 1].x;我的想法类似于document.querySelector("Line")[thisComponetIndex - 1].x; but isn't possible in Svelte since is compiled.但在 Svelte 中是不可能的,因为已编译。

If the lines are related, I would recommend processing them in a single component, rather than individually.如果这些行是相关的,我建议在单个组件中处理它们,而不是单独处理。 Inter-component communication in Svelte is a bit cumbersome. Svelte 中的组件间通信有点麻烦。

So instead of the current markup you do something like:因此,您可以执行以下操作,而不是当前标记:

<Lines items={[
    { x: 10, y: 12 },
    { x: 14, y: 8 },
    { x: 50, y: 30 },
]}/>

Then, inside the component you can process the items with {#each} and use its index to also access the previous item.然后,在组件内部,您可以使用{#each}处理项目并使用其索引来访问前一个项目。

{#each items as item, index}
  {@const previousItem = items[index - 1]}
  ...
{/each}

You can still use the Line component here, if that is useful to you.如果对您有用,您仍然可以在此处使用Line组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM