如何让 Svelte 像 React 一样更新输入组件? [英] How do I make Svelte update input components like React does?

查看:52
本文介绍了如何让 Svelte 像 React 一样更新输入组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望即时清理用户输入.考虑 这个 Svelte REPL 示例,我们尝试删除用户键入的所有 x.如果您输入x",则经过消毒的版本与原始版本相同,因此不会更新,但x"仍会显示在输入字段中.一旦您键入另一个字符,就会发生 更改,因此该字段将更新为删除了x".将此与 这个 React 沙箱进行比较,其中状态始终正确反映.

I'm looking to sanitise user input on the fly. Consider this Svelte REPL example where we attempt to remove all x's that the user types. If you type an "x", the sanitised version is the same as the original, so it doesn't update, but the "x" is still displayed in the input field. Once you type another character, there is a change, so the field is updated with the "x" removed. Compare this to this React sandbox where the state is always properly reflected.

如何在 Svelte 中获取 React 的行为?

技术上可以通过在玩具示例中写入 value 来解决这个问题(例如,通过使用双向绑定:bind:value={value}).这将导致 Svelte 更新 value 两次,第一次使用错误的值,然后 确实 触发失效代码,然后第二次使用正确的值.在我正在处理的场景中,我正在从只读的 Observable 中读取数据,因此无法选择 hack.您可以在在此 Svelte REPL 中使用这样的示例.

One could technically work around this issue by writing to value in the toy example (e.g. by having a two-way binding instead: bind:value={value}). That would cause Svelte to update value twice, first with the wrong value which then does trigger the invalidation code and then a second time with the right value. In the scenario I'm dealing with, I'm reading from an Observable which are read-only, so that hack is not an option. You can play around with such an example in this Svelte REPL.

推荐答案

您需要阻止事件的默认行为:

You need to prevent the event's default behaviour:

<script>
  let value = 'test';

  function sanitize(e) {
    e.preventDefault();
    value = e.target.value = e.target.value.replace(/x/g, '');
  }
</script>

<input
  value={value}
  on:input={sanitize}
/>

此处演示.

这篇关于如何让 Svelte 像 React 一样更新输入组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆