要清除 React 中的选择框的值,可以使用以下方法之一:
setState()
方法将选择框的值设置为初始值或空字符串。import React, { useState } from "react";
function MyComponent() {
const [selectedValue, setSelectedValue] = useState("");
const handleClearSelection = () => {
setSelectedValue("");
};
return (
<div>
<select value={selectedValue} onChange={(e) => setSelectedValue(e.target.value)}>
<option value="">-- Select --</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
<button onClick={handleClearSelection}>Clear Selection</button>
</div>
);
}
ref
来访问选择框的 DOM 元素,然后使用 element.value
将其值设置为空字符串。import React, { useRef } from "react";
function MyComponent() {
const selectRef = useRef(null);
const handleClearSelection = () => {
selectRef.current.value = "";
};
return (
<div>
<select ref={selectRef}>
<option value="">-- Select --</option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
<button onClick={handleClearSelection}>Clear Selection</button>
</div>
);
}
无论哪种方法,都可以在点击清除按钮时将选择框的值清除。