antd 如何拿到Form.Item 下的Select里的option
时间: 2024-03-12 19:48:16 浏览: 25
要获取 `Form.Item` 下的 `Select` 组件中的所有选项,可以通过 `React` 的 `ref` 属性来实现。具体步骤如下:
1. 在 `Form.Item` 中使用 `ref` 属性创建一个 `ref` 对象,如:
```
<Form.Item label="Label" name="name" ref={selectRef}>
<Select>
<Option value="value1">Option 1</Option>
<Option value="value2">Option 2</Option>
<Option value="value3">Option 3</Option>
</Select>
</Form.Item>
```
这里的 `selectRef` 是在 `useState` 中创建的,如:
```
const [selectRef, setSelectRef] = useState(null);
```
2. 在 `useEffect` 中等待 `Form.Item` 和 `Select` 组件渲染完成后,通过 `selectRef.current.props.children` 来获取 `Select` 组件下的所有 `Option` 组件,如:
```
useEffect(() => {
if (selectRef && selectRef.current) {
const options = Array.from(selectRef.current.props.children).map(option => {
return {
value: option.props.value,
label: option.props.children
}
});
console.log(options);
}
}, [selectRef]);
```
这里使用 `Array.from` 将 `Select` 的子组件转换为数组,然后遍历数组中的每个 `Option` 组件,将其值和标签存储在一个对象中,最后将所有对象存储在一个数组中并输出到控制台中。
注意:在 `useEffect` 中需要将 `selectRef` 作为依赖项传入,以确保 `Form.Item` 和 `Select` 组件渲染完成后再执行代码。