React Antd Form 中如何批量创建和获取 Input 组件的 ref?

antd,form中怎么用react获取多个input的ref?难道要一个一个创建useRef,然后给input吗?

有没有统一给form里面的所有控件创建ref,然后通过某个关键字获取相应input的ref

阅读 1.6k
2 个回答

可以通过数据抽象一次性处理:

import React, { useEffect, useMemo } from 'react';
import { Form, Input, InputRef } from 'antd';

export function Demo() {
  const inputRefs = useMemo<Map<string, InputRef | null>>(() => new Map(), []);

  const items = [
    {
      name: 'xxx',
    },
    {
      name: 'yyy',
    },
  ];

  useEffect(() => {
    console.log(inputRefs);
  }, []);

  return (
    <Form>
      {items.map((item) => (
        <Form.Item name={item.name} key={item.name}>
          <Input
            ref={(ref) => {
              inputRefs.set(item.name, ref);
            }}
          />
        </Form.Item>
      ))}
    </Form>
  );
}

如果组件结构差异比较大,没法通过数据统一,只能通过工具方法简化了:

import React, { useEffect, useMemo } from 'react';
import { Form, Input, InputRef } from 'antd';

export function Demo() {
  const inputRefs = useMemo<Map<string, InputRef | null>>(() => new Map(), []);

  useEffect(() => {
    console.log(inputRefs);
  }, []);

  const refCallback = (name: string) => {
    return (ref: InputRef) => {
      inputRefs.set(name, ref);
    };
  };

  return (
    <Form>
      <Form.Item name="xxx">
        <Input ref={refCallback('xxx')} />
      </Form.Item>
      <Form.Item name="yyy">
        <Input ref={refCallback('yyy')} />
      </Form.Item>
    </Form>
  );
}

ref定义为一个表单控件名称->ref的映射

import { Form, Input, Radio } from 'antd';
import './App.css';
import { useEffect, useRef } from 'react';

function App() {
  const formControlRefs = useRef<Record<string, any>>({});

  useEffect(() => {
    console.log('formControlRefs: ', formControlRefs.current);
    console.log('username ref: ', formControlRefs.current['username']);
  }, []);
  return (
    <Form>
      <Form.Item name="username">
        <Input
          ref={(ref) => {
            formControlRefs.current['username'] = ref;
          }}
        />
      </Form.Item>
      <Form.Item name="bio">
        <Input
          ref={(ref) => {
            formControlRefs.current['bio'] = ref;
          }}
        />
      </Form.Item>
      <Form.Item name="gender">
        <Radio.Group
          ref={(ref) => {
            formControlRefs.current['gender'] = ref;
          }}
          options={[
            { label: '男', value: 1 },
            { label: '女', value: 2 },
          ]}
        />
      </Form.Item>
    </Form>
  );
}

export default App;

Logs:

image.png

stackblitz

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏