gpt4 book ai didi

svelte - 错误 : 'type' attribute cannot be dynamic if input uses two-way binding

转载 作者:行者123 更新时间:2023-12-04 22:02:46 34 4
gpt4 key购买 nike

我试图创建一个 Input我的项目的组件。我想在 input 上动态设置类型属性元素

但是当我在 input 上动态设置类型属性时我得到错误说'type' attribute cannot be dynamic if input uses two-way binding
那么有什么解决方法可以让我动态设置类型属性而不会丢失双向绑定(bind)
Input.svelte

<script>
export let placeholder = "";
export let label = "";
export let description = "";
export let value = "";
export let type = "text";
</script>

<div class="container">
<label>{label}</label>
<input {type} bind:value {placeholder} />
<p>{description}</p>
</div>

最佳答案

原因type双向绑定(bind)必须是静态的,因为 Svelte 生成的代码对于不同类型的输入是不同的。例如,numberrange输入必须将其值强制转换为数字,某些输入需要 change事件监听器而不是 input事件或反之亦然,等等。

但是您可以手动执行生成的代码会执行的相同操作——添加一个反射(reflect)状态的事件监听器:

<script>
export let placeholder = "";
export let label = "";
export let description = "";
export let value = "";
export let type = "text";

const handleInput = e => {
// in here, you can switch on type and implement
// whatever behaviour you need
value = type.match(/^(number|range)$/)
? +e.target.value
: e.target.value;
};
</script>

<div class="container">
<label>{label}</label>
<input {type} {value} {placeholder} on:input={handleInput} />
<p>{description}</p>
</div>

关于svelte - 错误 : 'type' attribute cannot be dynamic if input uses two-way binding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57392773/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com