我創建了一個輸入,當您正確并單擊按鈕時,值會添加到我們的狀態中,現在我嘗試從狀態中更新選擇選項,如下所示:
const NewGroup = () => {
const [group, setGroup] = useState([]);
const addToGroup = (e) => {
const newGroup = group;
newGroup.push(e.target.previousElementSibling.value);
setGroup(newGroup);
};
return (
<div>
<input type="text" name="" id="" />
<button onClick={addToGroup}>submit</button>
<div>
<select name="" id="">
{group.map((category) => {
return <option value=''>{category}</option>;
})}
</select>
</div>
</div>
);
};
export default NewGroup;
但什么也沒發生。
uj5u.com熱心網友回復:
您可以引入另一個useState()用于寫入<input>元素。當按下提交按鈕時,您只需將 推someText送到group陣列。
const NewGroup = () => {
const [group, setGroup] = useState([]);
const [someText, setSomeText] = useState("");
const addToGroup = (e) => {
// Takes up all the present elements(of array group) and adds new element (search)
let temp = [...group, someText];
setGroup(temp);
};
return (
<div>
<input type="text" name="" id="" value={someText} onChange={(e) => { setSomeText(e.target.value); }} />
<button onClick={addToGroup}>submit</button>
<div>
<select name="" id="">
{group.map((category, index) => {
return (
<option key={index} value="">
{category}
</option>
);
})}
</select>
</div>
</div>
);
}
export default NewGroup;
這是作業應用程式的鏈接https://codesandbox.io/s/boring-ptolemy-0cwzmi?file=/src/App.js
uj5u.com熱心網友回復:
首先,您不應該通過直接使用 DOM 來獲取輸入的值,而應該使用 Ref.
其次,問題是您直接改變組值而不是復制它。當你呼叫 setGroup 時,React 并沒有意識到有任何變化(因為之前的值等于當前值)。相反,您想復制陣列并添加新元素:
// Previously: const newGroup = group;
const newGroup = [...group];
這應該是讓您的代碼正常作業所要做的一切。但是,我使用下面的行內注釋對其進行了簡化和清理。
const NewGroup = () => {
// Here's where our input will be stored so we can use it later (instead of querying the dom directly)
const inputRef = React.useRef();
const [group, setGroup] = React.useState([]);
// Use React.useCallback so the function doesn't change on every render
const addToGroup = React.useCallback((e) => {
// We call setGroup with a function that returns the new group value. The first argument is the current group value. We return a new array by spreading the existing value and adding our new value
setGroup((v) => [...v, inputRef.current.value]);
}, []);
return (
<div>
<input type="text" ref={inputRef} name="" id="" />
<button onClick={addToGroup}>submit</button>
<div>
<select name="" id="">
{group.map((category) => {
return (
<option value="" key={category}>
{category}
</option>
);
})}
</select>
</div>
</div>
);
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/435725.html
標籤:javascript 数组 反应 状态 选择选项
