javascript - 如何将元素宽度作为道具传递?
问题描述
我正在尝试将表格单元格的宽度作为道具传递给其中的组件:
<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>
如何在生命周期方法中访问该号码?
解决方案
这是一个棘手的案例。执行顺序onMount
和初始afterUpdate
是子级在父级之前执行。这是有道理的,因为从概念上讲,每个子级都需要在父级完成其挂载之前挂载。
在您的情况下,只有在安装父组件后才知道值,因为计算cellWidth
宽度需要节点存在于 DOM 中。这意味着您不能为此使用或首字母,而且当从父级开始设置时,Svelte 似乎不会触发另一个。onMount
afterUpdate
afterUpdate
cellWidth
因此,解决方案取决于您想要实现的目标。一种可能性是提供一个函数,如果变量尚未初始化,则在短暂超时后再次执行/尝试,或者您使用反应性语句,该语句将在每次更改该变量后执行(可能是更好的选择)。
<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>
推荐阅读
- java - 如何在android studio中将分数中的3 int添加到总分中
- react-native-ios - clang:错误:没有输入文件,React Native 0.59.9 YGFloatOptional.cpp 文件未找到,react native ios 错误
- javascript - 构建动态剑道网格时模板无效
- css - CSS 特异性测试
- python - 在python运行时将数据从GUI传递给线程
- c# - Socket.BeginReceive:如果数据未通过则超时?
- unity3d - 防止变量在另一个场景负载上发生变化
- api - 无法从本地 api React-Native 获取数据
- java - Spring容器在引入切面后不注入依赖
- sockets - 大/小端转换在哪一层完成?