内置浏览器 <select>
组件 允许你渲染带有选项的选择框。
¥The built-in browser <select>
component lets you render a select box with options.
<select>
<option value="someOption">Some option</option>
<option value="otherOption">Other option</option>
</select>
参考
¥Reference
<select>
要显示选择框,请渲染 内置浏览器 <select>
组件。
¥To display a select box, render the built-in browser <select>
component.
<select>
<option value="someOption">Some option</option>
<option value="otherOption">Other option</option>
</select>
属性
¥Props
<select>
支持所有 普通元素属性。
¥<select>
supports all common element props.
你可以通过传递 value
属性来 控制选择框:
¥You can make a select box controlled by passing a value
prop:
-
value
:字符串(或multiple={true}
的字符串数组)。控制选择哪个选项。每个值字符串都匹配<select>
中嵌套的某些<option>
的value
。¥
value
: A string (or an array of strings formultiple={true}
). Controls which option is selected. Every value string match thevalue
of some<option>
nested inside the<select>
.
当你传递 value
时,你还必须传递一个更新传递值的 onChange
处理程序。
¥When you pass value
, you must also pass an onChange
handler that updates the passed value.
如果你的 <select>
不受控制,你可以传递 defaultValue
属性:
¥If your <select>
is uncontrolled, you may pass the defaultValue
prop instead:
-
defaultValue
:字符串(或multiple={true}
的字符串数组)。指定 最初选择的选项。¥
defaultValue
: A string (or an array of strings formultiple={true}
). Specifies the initially selected option.
这些 <select>
属性与不受控制和受控制的选择框相关:
¥These <select>
props are relevant both for uncontrolled and controlled select boxes:
-
autoComplete
:一个字符串。指定可能的 自动补齐行为。 之一¥
autoComplete
: A string. Specifies one of the possible autocomplete behaviors. -
autoFocus
:一个布尔值。如果是true
,React 会将元素集中在挂载上。¥
autoFocus
: A boolean. Iftrue
, React will focus the element on mount. -
children
:<select>
接受<option>
、<optgroup>
和<datalist>
组件作为子级。你也可以传递自己的组件,只要它们最终渲染允许的组件之一。如果你传递自己的最终渲染<option>
标签的组件,那么你渲染的每个<option>
都必须有一个value
。¥
children
:<select>
accepts<option>
,<optgroup>
, and<datalist>
components as children. You can also pass your own components as long as they eventually render one of the allowed components. If you pass your own components that eventually render<option>
tags, each<option>
you render must have avalue
. -
disabled
:一个布尔值。如果是true
,选择框将不会是交互式的,并且会显示为灰色。¥
disabled
: A boolean. Iftrue
, the select box will not be interactive and will appear dimmed. -
form
:一个字符串。指定此选择框所属的<form>
的id
。如果省略,它是最接近的父表单。¥
form
: A string. Specifies theid
of the<form>
this select box belongs to. If omitted, it’s the closest parent form. -
multiple
:一个布尔值。如果true
,浏览器允许 多项选择。¥
multiple
: A boolean. Iftrue
, the browser allows multiple selection. -
¥
name
: A string. Specifies the name for this select box that’s submitted with the form. -
onChange
:一个Event
处理程序 函数。控制选择框。 需要当用户选择不同的选项时立即触发。行为类似于浏览器input
事件。¥
onChange
: AnEvent
handler function. Required for controlled select boxes. Fires immediately when the user picks a different option. Behaves like the browserinput
event. -
onChangeCapture
:在 捕获阶段。 中触发的onChange
版本¥
onChangeCapture
: A version ofonChange
that fires in the capture phase. -
onInput
:一个Event
处理程序 函数。当用户更改值时立即触发。由于历史原因,在 React 中惯用的是使用onChange
,它的工作方式类似。¥
onInput
: AnEvent
handler function. Fires immediately when the value is changed by the user. For historical reasons, in React it is idiomatic to useonChange
instead which works similarly. -
onInputCapture
:在 捕获阶段。 中触发的onInput
版本¥
onInputCapture
: A version ofonInput
that fires in the capture phase. -
onInvalid
:一个Event
处理程序 函数。如果输入在表单提交时验证失败,则触发。与内置的invalid
事件不同,ReactonInvalid
事件冒泡。¥
onInvalid
: AnEvent
handler function. Fires if an input fails validation on form submit. Unlike the built-ininvalid
event, the ReactonInvalid
event bubbles. -
onInvalidCapture
:在 捕获阶段。 中触发的onInvalid
版本¥
onInvalidCapture
: A version ofonInvalid
that fires in the capture phase. -
required
:一个布尔值。如果是true
,则必须提供该值以便提交表单。¥
required
: A boolean. Iftrue
, the value must be provided for the form to submit. -
size
:一个号码。对于multiple={true}
选择,指定最初可见项目的首选数量。¥
size
: A number. Formultiple={true}
selects, specifies the preferred number of initially visible items.
注意事项
¥Caveats
-
与 HTML 不同,不支持将
selected
属性传递给<option>
。而是,对不受控制的选择框使用<select defaultValue>
,对受控的选择框使用<select value>
。¥Unlike in HTML, passing a
selected
attribute to<option>
is not supported. Instead, use<select defaultValue>
for uncontrolled select boxes and<select value>
for controlled select boxes. -
如果选择框收到
value
属性,它将是 作为控制处理。¥If a select box receives a
value
prop, it will be treated as controlled. -
选择框不能同时受控和不受控。
¥A select box can’t be both controlled and uncontrolled at the same time.
-
选择框在其生命周期内无法在受控或不受控之间切换。
¥A select box cannot switch between being controlled or uncontrolled over its lifetime.
-
每个受控的选择框都需要一个
onChange
事件处理程序来同步更新其支持值。¥Every controlled select box needs an
onChange
event handler that synchronously updates its backing value.
用法
¥Usage
显示带有选项的选择框
¥Displaying a select box with options
渲染一个 <select>
,其中包含一个 <option>
组件列表,以显示一个选择框。给每个 <option>
一个 value
,代表要随表单提交的数据。
¥Render a <select>
with a list of <option>
components inside to display a select box. Give each <option>
a value
representing the data to be submitted with the form.
export default function FruitPicker() { return ( <label> Pick a fruit: <select name="selectedFruit"> <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="orange">Orange</option> </select> </label> ); }
为选择框提供标签
¥Providing a label for a select box
通常,你会将每个 <select>
放在 <label>
标签中。这告诉浏览器这个标签与那个选择框相关联。当用户点击标签时,浏览器会自动聚焦选择框。它对于可访问性也很重要:当用户聚焦选择框时,屏幕阅读器将宣布标签标题。
¥Typically, you will place every <select>
inside a <label>
tag. This tells the browser that this label is associated with that select box. When the user clicks the label, the browser will automatically focus the select box. It’s also essential for accessibility: a screen reader will announce the label caption when the user focuses the select box.
如果不能将 <select>
嵌套到 <label>
中,通过将相同的 ID 传递给 <select id>
和 <label htmlFor>
。 来关联它们 为了避免一个组件的多个实例之间的冲突,使用 useId
。 生成这样的 ID
¥If you can’t nest <select>
into a <label>
, associate them by passing the same ID to <select id>
and <label htmlFor>
. To avoid conflicts between multiple instances of one component, generate such an ID with useId
.
import { useId } from 'react'; export default function Form() { const vegetableSelectId = useId(); return ( <> <label> Pick a fruit: <select name="selectedFruit"> <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="orange">Orange</option> </select> </label> <hr /> <label htmlFor={vegetableSelectId}> Pick a vegetable: </label> <select id={vegetableSelectId} name="selectedVegetable"> <option value="cucumber">Cucumber</option> <option value="corn">Corn</option> <option value="tomato">Tomato</option> </select> </> ); }
提供最初选择的选项
¥Providing an initially selected option
默认情况下,浏览器会选择列表中的第一个 <option>
。要默认选择不同的选项,请将 <option>
的 value
作为 defaultValue
传递给 <select>
元素。
¥By default, the browser will select the first <option>
in the list. To select a different option by default, pass that <option>
’s value
as the defaultValue
to the <select>
element.
export default function FruitPicker() { return ( <label> Pick a fruit: <select name="selectedFruit" defaultValue="orange"> <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="orange">Orange</option> </select> </label> ); }
启用多选
¥Enabling multiple selection
将 multiple={true}
传递给 <select>
让用户选择多个选项。在这种情况下,如果你还指定 defaultValue
来选择最初选择的选项,则它必须是一个数组。
¥Pass multiple={true}
to the <select>
to let the user select multiple options. In that case, if you also specify defaultValue
to choose the initially selected options, it must be an array.
export default function FruitPicker() { return ( <label> Pick some fruits: <select name="selectedFruit" defaultValue={['orange', 'banana']} multiple={true} > <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="orange">Orange</option> </select> </label> ); }
提交表单时读取选择框的值
¥Reading the select box value when submitting a form
在你的选择框周围添加一个 <form>
,里面有一个 <button type="submit">
。它将调用你的 <form onSubmit>
事件处理程序。默认情况下,浏览器会将表单数据发送到当前 URL 并刷新页面。你可以通过调用 e.preventDefault()
来覆盖该行为。使用 new FormData(e.target)
读取表单数据。
¥Add a <form>
around your select box with a <button type="submit">
inside. It will call your <form onSubmit>
event handler. By default, the browser will send the form data to the current URL and refresh the page. You can override that behavior by calling e.preventDefault()
. Read the form data with new FormData(e.target)
.
export default function EditPost() { function handleSubmit(e) { // Prevent the browser from reloading the page e.preventDefault(); // Read the form data const form = e.target; const formData = new FormData(form); // You can pass formData as a fetch body directly: fetch('/some-api', { method: form.method, body: formData }); // You can generate a URL out of it, as the browser does by default: console.log(new URLSearchParams(formData).toString()); // You can work with it as a plain object. const formJson = Object.fromEntries(formData.entries()); console.log(formJson); // (!) This doesn't include multiple select values // Or you can get an array of name-value pairs. console.log([...formData.entries()]); } return ( <form method="post" onSubmit={handleSubmit}> <label> Pick your favorite fruit: <select name="selectedFruit" defaultValue="orange"> <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="orange">Orange</option> </select> </label> <label> Pick all your favorite vegetables: <select name="selectedVegetables" multiple={true} defaultValue={['corn', 'tomato']} > <option value="cucumber">Cucumber</option> <option value="corn">Corn</option> <option value="tomato">Tomato</option> </select> </label> <hr /> <button type="reset">Reset</button> <button type="submit">Submit</button> </form> ); }
使用状态变量控制选择框
¥Controlling a select box with a state variable
像 <select />
这样的选择框是不受控制的。即使你 传递最初选择的值 喜欢 <select defaultValue="orange" />
,你的 JSX 也只是指定了初始值,而不是现在的值。
¥A select box like <select />
is uncontrolled. Even if you pass an initially selected value like <select defaultValue="orange" />
, your JSX only specifies the initial value, not the value right now.
要渲染受控选择框,请将 value
属性传递给它。React 将强制选择框始终包含你传递的 value
。通常,你将通过声明 状态变量 来控制选择框
¥To render a controlled select box, pass the value
prop to it. React will force the select box to always have the value
you passed. Typically, you will control a select box by declaring a state variable:
function FruitPicker() {
const [selectedFruit, setSelectedFruit] = useState('orange'); // Declare a state variable...
// ...
return (
<select
value={selectedFruit} // ...force the select's value to match the state variable...
onChange={e => setSelectedFruit(e.target.value)} // ... and update the state variable on any change!
>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="orange">Orange</option>
</select>
);
}
如果你想要重新渲染 UI 的某些部分以响应每个选择,这将很有用。
¥This is useful if you want to re-render some part of the UI in response to every selection.
import { useState } from 'react'; export default function FruitPicker() { const [selectedFruit, setSelectedFruit] = useState('orange'); const [selectedVegs, setSelectedVegs] = useState(['corn', 'tomato']); return ( <> <label> Pick a fruit: <select value={selectedFruit} onChange={e => setSelectedFruit(e.target.value)} > <option value="apple">Apple</option> <option value="banana">Banana</option> <option value="orange">Orange</option> </select> </label> <hr /> <label> Pick all your favorite vegetables: <select multiple={true} value={selectedVegs} onChange={e => { const options = [...e.target.selectedOptions]; const values = options.map(option => option.value); setSelectedVegs(values); }} > <option value="cucumber">Cucumber</option> <option value="corn">Corn</option> <option value="tomato">Tomato</option> </select> </label> <hr /> <p>Your favorite fruit: {selectedFruit}</p> <p>Your favorite vegetables: {selectedVegs.join(', ')}</p> </> ); }