我在使用 Svelte 5 组件时遇到了一个奇怪的问题,即页面加载时,表单会在屏幕上短暂闪烁约半秒钟,然后消失。当我对图像进行条件渲染(使用 {#if})并且 bind:value={name} 时会发生这种情况,如果我同时删除这两个,表单就会出现。
<script>
let name = $state('');
let name2 = 'test';
</script>
<body>
<div class="container">
{#if name.toLowerCase() === name2.toLowerCase()}
<img src="example" alt="fantasma" class="fantasma" />
{/if}
<div class="box">
<form class="form-group" action="">
<label for="name" class="pergunta">Seu nome completo</label>
<input type="text" id="name" class="input" bind:value={name} />
<label for="date" class="pergunta">data de nascimento</label>
<input type="date" id="data" class="input" />
</form>
</div>
</div>
</body>
<style>
.fantasma {
width: 24%;
height: auto;
}
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
flex-direction: column;
background-color: #f0f0f0;
margin: 0;
}
.form-group {
display: flex;
flex-direction: column;
align-items: center;
}
.pergunta {
margin-bottom: 7px;
}
.input {
width: 300px;
margin-bottom: 20px;
}
.box {
width: 370px;
height: 180px;
margin: 40px;
align-items: center;
display: flex;
flex-direction: column;
justify-content: center;
border-radius: 10px;
background-color: red;
border: 2.13px solid #ccc;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
</style>
我知道,name 最初为空 (''),因此条件 name.toLowerCase() === name2.toLowerCase() 的计算结果为 false。这会阻止图像渲染,这是预期的行为。但是,我不明白为什么这会导致表单在短暂出现后消失。似乎条件渲染在某种程度上干扰了表单本身的初始渲染。
我尝试过的:
- 删除 {#if} 块:不能解决问题。
- 删除 bind:value={name}: 并不能解决问题。
- 删除 {#if} 和 bind:value:解决了表单消失的问题,但显然删除了条件图像显示。
通常,组件中不应有
<body>
。使用 SvelteKit 时, 中已经有一个app.html
,添加另一个可能会导致水合时出现运行时错误(检查浏览器控制台)。您最初看到的是服务器端渲染的 HTML,浏览器通过删除重复的 body 标签来修复它。一旦 JS 加载并尝试补充页面,它就会遍历 DOM 以查找现在没有的元素。