Svelte格式文本输入

huangapple go评论60阅读模式
英文:

Svelte format text input

问题

I'm looking to create a text input that formats the inputted value as the user inputs it. As the formatting function strips additional characters from the string the input value doesn't update. A bit of a contrived example, repl link

<script>
	let value = "[hello]"	
	const parse = (value) => value.replace(/[\[\]&]+/g, '');
	let parsed = parse('[hello]');
	const onChange = (event) => {
		parsed = parse(event.target.value);
	};
</script>

<h1>{parsed}</h1>
<input type="text" value={parsed} on:input={onChange} />
英文:

I'm looking to create a text input that formats the inputted value as the user inputs it. As the formatting function strips additional characters from the string the input value doesn't update. A bit of a contrived example, repl link

<script>
	let value = "[hello]"	
	const parse = (value) => value.replace(/[\[\]&]+/g, '');
	let parsed = parse('[hello]');
	const onChange = (event) => {
		parsed = parse(event.target.value);
	};
</script>

<h1>{parsed}</h1>
<input type="text" value={parsed} on:input={onChange} />

The onChange function strips the square brackets from the string but the value in the input doesn't update if I type brackets into the input, I assume since they are stripped the value of parsed remains the same so doesn't trigger an update. I thought about putting it inside a key block but then I'd have to track the position of the cursor, is there another solution?

答案1

得分: 2

尝试改成这样,并查阅 Svelte 中的双向数据绑定。

<script>
    let value = "[hello]";
    // 从字符串中移除任何方括号
    const parse = (value) => value.replace(/[\[\]&amp;]+/g, '');
    let parsed = parse('[hello]');
    const onChange = () => {
        parsed = parse(parsed);
    };
</script>

<h1>{parsed}</h1>
<input type="text" bind:value={parsed} on:input={onChange} />

这是你提供的代码的翻译部分。

英文:

Try this instead, and look up two way data binding in Svelte.

&lt;script&gt;
	let value = &quot;[hello]&quot;	
	// strips any square brackets from string
	const parse = (value) =&gt; value.replace(/[\[\]&amp;]+/g, &#39;&#39;);
	let parsed = parse(&#39;[hello]&#39;);
	const onChange = () =&gt; {
		parsed = parse(parsed);
	};
&lt;/script&gt;

&lt;h1&gt;{parsed}&lt;/h1&gt;
&lt;input type=&quot;text&quot; bind:value={parsed} on:input={onChange} /&gt;

huangapple
  • 本文由 发表于 2023年3月4日 01:15:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75630062.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定