首页 > 解决方案 > 如何将元素宽度作为道具传递?

问题描述

我正在尝试将表格单元格的宽度作为道具传递给其中的组件:

 <td bind:clientWidth={cellWidth}>
        <NestedComponent cellWidth={cellWidth} />
  </td>

然后在嵌套组件中,我尝试通过 lyfecycle 方法访问它,但它记录为未定义

<script lang="ts">
import { afterUpdate, onMount } from "svelte";
  export let cellWidth;
  
  let listWidth;
  
  onMount(()=> {
    console.log('cellWidth', cellWidth);
  })

  afterUpdate(() => {
    console.log('cellWidth', cellWidth);
  }) 

</script>

但是,如果我在组件内渲染宽度,它将显示宽度

<div>{cellWidth}</div>

如何在生命周期方法中访问该号码?

标签: javascriptsvelte

解决方案


这是一个棘手的案例。执行顺序onMount和初始afterUpdate是子级在父级之前执行。这是有道理的,因为从概念上讲,每个子级都需要在父级完成其挂载之前挂载。

在您的情况下,只有在安装父组件后才知道值,因为计算cellWidth宽度需要节点存在于 DOM 中。这意味着您不能为此使用或首字母,而且当从父级开始设置时,Svelte 似乎不会触发另一个。onMountafterUpdateafterUpdatecellWidth

因此,解决方案取决于您想要实现的目标。一种可能性是提供一个函数,如果变量尚未初始化,则在短暂超时后再次执行/尝试,或者您使用反应性语句,该语句将在每次更改该变量后执行(可能是更好的选择)。

<script>
  import { afterUpdate } from "svelte";

  export let cellWidth;

  // Option 1
  function logCellWidth() {
    if (cellWidth === undefined) {
      setTimeout(() => logCellWidth(), 100);
    } else {
      console.log('cellWidth1', cellWidth);
    }
  }

  afterUpdate(logCellWidth);

  // Option 2
  $: cellWidth !== undefined && console.log('cellWidth2', cellWidth);

</script>

推荐阅读