我一直在嘗試制作一個表單,根據一個開關按鈕,呈現一個或兩個不同的輸入。我的代碼如下所示:
const Test = () => {
const [switchButton, setSwitch] = React.useState(true)
const handleSwitch = () => {setstate(!switchButton)}
return <>
<Switch checked={switchButton} onClick={() => handleSwitch} />
{!switchButton ?
<>
<label htmlFor="input_1">Input 1</label>
<input id="input_1"/>
</>
:
<>
<label htmlFor="input_2">Input 2</label>
<input id="input_2" />
<label htmlFor="input_3">Input 3</label>
<input id="input_3" />
</>
}
</>
}
export default Test;
當我在一個輸入中輸入字符然后切換它們時會出現我的問題:相同的字符顯示在我的新渲染輸入上。例子在這里。
為什么會發生這種情況?我真的迷路了
uj5u.com熱心網友回復:
為元素使用鍵,因此它不會被識別為與 react 嘗試在每次重新渲染時映射元素(如果它們之前已經渲染過)相同的元素。所以反應看到:1 個輸入而不是 2 個輸入,并認為第一個輸入與以前相同。
const Test = () => {
const [switchButton, setSwitch] = React.useState(true)
const handleSwitch = () => setSwitch((switch) => !switch)
return (
<>
<Switch checked={switch} onClick={handleSwitch} />
{!switchButton ? (
<React.Fragment key="key1">
<label htmlFor="input_1">Input 1</label>
<input id="input_1"/>
</>
) : (
<React.Fragment key="key2">
<label htmlFor="input_2">Input 2</label>
<input id="input_2" />
<label htmlFor="input_3">Input 3</label>
<input id="input_3" />
</>
)}
</>
)}
export default Test;
但無論如何最好使用受控輸入。像這樣:
const [value, setValue] = React.useState(true)
<input value={value} onChange={(e) => setValue(e.target.value)}/>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/330790.html
標籤:javascript 反应
