問題描述
React.js 更改下拉值 (React.js to change dropdown value)
我正在嘗試使用 React useState 更改下拉值的值,但看起來它在調用 onClick 後刷新了頁面。例如,當我單擊選項 B 時,它會將 selectedValue 狀態更改為 B,然後重新渲染頁面並將其重置為默認值。我的問題是為什麼它重新呈現頁面?以及如何更改下拉值?
import React, {useState} from 'react';
function InputDropdown(props) {
const [selectedValue, setSelectedValue] = useState("");
return (
<div className="input‑group">
<input type="text" className="form‑control" />
<div className="input‑group‑append">
<button type="button" className="btn btn‑outline‑secondary">{selectedValue}</button>
<button type="button" className="btn btn‑outline‑secondary dropdown‑toggle dropdown‑toggle‑split" data‑toggle="dropdown">
<span className="sr‑only">Toggle Dropdown</span>
</button>
<div className="dropdown‑menu">
<a class="dropdown‑item" href="#" onClick={() =>setSelectedValue("A")}>A</a>
<a class="dropdown‑item" href="#" onClick={() =>setSelectedValue("B")}>B</a>
<a class="dropdown‑item" href="#" onClick={() =>setSelectedValue("C")}>C</a>
</div>
</div>
</div>
)
}
參考解法
方法 1:
In React, if any state value changed, the component will be re‑rendered. That's why your new state value will be refreshed on the page.
In your example, selectedValue
is empty at the beginning.
when you selected a value, you called setSelectedValue()
(beware your option B value is C may be a bug)
it changed the selectedValue
local state's value, the component re‑rendreed. That's why after re‑rendered, on your button the value changed to your selected value.
(by user3818381、Eric Cheng)