在 Svelte 中,有沒有辦法撤銷無效的用戶輸入,而不觸發狀態的暫時假屬性更改?
例如(在線試用),當用戶型別123a的input箱子,我想它隱蔽的電話號碼,并分配給它counter。
為此,我必須引入一個臨時和冗余的更改counter(使用Number.NaN下面)。否則,counter不會改變,123a并將保留在input框內,而我想將其恢復為123:
<script>
let count = 0;
const handleClick = () => count ;
const handleChange = async e => {
const userValue = e.target.value;
let newValue = userValue? parseInt(userValue): 0;
if (isNaN(newValue)) newValue = count;
count = Number.NaN;
await Promise.resolve();
count = newValue;
};
</script>
Count: <button on:click={handleClick}>{count}</button>
<br />
A: <input value={count} on:input={handleChange} />
<br />
有更好的方法嗎?本質上,我想為我的 Svetle 組件的一部分觸發手動重新渲染,而不改變狀態。
當然,在事件處理程式中,我可以通過e.target.value直接修改來撤消更改:
const handleChange = async e => {
const userValue = e.target.value;
let newValue = userValue? parseInt(userValue): 0;
if (isNaN(newValue)) newValue = count;
if (newValue == count)
e.target.value = count;
else
count = newValue;
};
但我想知道是否有辦法告訴 Svelte 重新渲染整體<input>?
為了進行比較,以下是我如何在 React 中做到這一點(在線嘗試):
function App() {
let [count, setCount] = useState(0);
const handleClick = () => setCount((count) => count 1);
const handleChange = (e) => {
const userValue = e.target.value;
let newValue = userValue ? parseInt(userValue) : 0;
if (isNaN(newValue)) newValue = count;
setCount(newValue);
};
return (
<>
Count: <button onClick={handleClick}>{count}</button>
<br />
A: <input value={count} onInput={handleChange} />
<br />
</>
);
}
uj5u.com熱心網友回復:
您只需要bind計算輸入的值。復制代碼
<script>
let count = 0;
const handleClick = () => count ;
const handleChange = (e) => {
const userValue = e.target.value;
const newValue = userValue ? parseInt(userValue, 10) : 0;
count = isNaN(newValue) ? count : newValue;
};
</script>
Count: <button on:click={handleClick}>{count}</button>
<br />
A: <input bind:value={count} on:input={handleChange} />
<br />
注意:請記住始終將基數傳遞給parseInt(),它不會默認為 10。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/360493.html
標籤:javascript 反应 状态 苗条的
上一篇:Map()回傳重復的組件
