React Antd Form中如何同时获取Select选项的Value与Label?
如何获取antd-form-builder中Select选中项的Label
方法1:直接从现有配置里匹配
你已经在meta里定义了Select的选项列表,点击按钮时直接用拿到的value去数组里找对应的label就行:
const handleClick = () => { const taskValue = form.getFieldValue("task"); // 定位到task字段的配置 const taskField = meta.fields.find(field => field.key === "task"); if (taskField && taskValue !== undefined) { // 匹配对应的选项 const selectedOption = taskField.options.find(opt => opt.value === taskValue); const taskLabel = selectedOption?.label || ""; console.log("选中值:", taskValue); console.log("对应标签:", taskLabel); } };
方法2:用onChange提前存好Label
如果不想每次点击都遍历数组,可以给Select加个onChange事件,把选中的Label存到状态里,用的时候直接取:
import { useState } from 'react'; // 新增状态存Label const [taskLabel, setTaskLabel] = useState(""); const meta = { fields: [ { key: "task", label: "Task", widget: "select", widgetProps: { showSearch: true, onChange: (value, option) => { // 选的时候直接把Label存起来 setTaskLabel(option.label); } }, options: [ { label: "Pre-filter Replacement", value: 1 }, { label: "Oil Change", value: 2 }, ], }, ] }; const handleClick = () => { const taskValue = form.getFieldValue("task"); console.log("选中值:", taskValue); console.log("对应标签:", taskLabel); };
两种方法的区别
- 方法1不用额外维护状态,直接复用现有配置,适合选项固定的场景。
- 方法2避免重复遍历数组,性能更好,适合需要频繁获取Label的场景。
内容的提问来源于stack exchange,提问作者Andish
相关产品推荐
相关产品推荐

