如何让 Svelte 像 React 一样更新输入组件?

How do I make Svelte update input components like React does?

我希望即时清理用户输入。考虑 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 始终正确反映状态的地方。

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

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

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

<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}
/>

Demo here.

您可以使用 beforeinput 事件:

<script>
    let value = 'test';

    function sanitize(e) {
        if (e.data.includes('x')) e.preventDefault();
    }
</script>

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

Demo