英文:
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(/[\[\]&]+/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.
<script>
let value = "[hello]"
// strips any square brackets from string
const parse = (value) => value.replace(/[\[\]&]+/g, '');
let parsed = parse('[hello]');
const onChange = () => {
parsed = parse(parsed);
};
</script>
<h1>{parsed}</h1>
<input type="text" bind:value={parsed} on:input={onChange} />
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论