React:AutoFocus 在 Modal 内的输入字段上

React: AutoFocus on Input field inside Modal

我用的是Antd。我有 Modal Window,其中包含 Form。当用户打开模式窗口时,我想专注于输入字段。我如何在功能组件中做到这一点?我尝试了这个但对我不起作用:


const EditForm = ({visible, widget, onSave, onCancel}) => {
  const nameInput = useRef();
  useEffect(() => nameInput.current && nameInput.current.focus());
  const [form] = Form.useForm();
   return (
    <div>
      <Modal
        visible={visible}
        title='Edit'
        okText='Save'
        cancelText='Cancel'
        onCancel={onCancel}
        onOk={() => {
          form
            .validateFields()
            .then(values => {
              form.resetFields();
              onSave(values);
            })
            .catch(info => {
              console.log('Validate Failed:', info);
            });
        }}
      >
        <Form
          {...formItemLayout}
          layout={formLayout}
          form={form}
        >
          <Form.Item />
          <Form.Item
            name='nameWidget'
            label='Name'
          >
            <Input name='nameWidget' ref={nameInput} onChange={handleChangeName} placeholder='Введите новое название' />
          </Form.Item>

        </Form>
      </Modal>
    </div>
  );
};

试试这个方法。 祝你好运;)

import React, {useState, useRef, useEffect}  from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Modal, Button, Input, Form } from 'antd';


const App = () => {
  const [visible, setVisible] = useState(false)
  const myRef = useRef();

  /*
   *  This is the main different
   */
  useEffect(()=>{
    if (myRef && myRef.current) {
      const { input } = myRef.current
      input.focus()
    }

  })
  const showModal = () => {
    setVisible(true)
  };

  const handleOk = e => {
    setVisible(false)
  };

  const handleCancel = e => {
    setVisible(false)
  };

  return (
    <>
      <Button type="primary" onClick={showModal}>
        Open Modal with customized button props
      </Button>
      <Modal
        title="Basic Modal"
        visible={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        okButtonProps={{ disabled: true }}
        cancelButtonProps={{ disabled: true }}
      >
        <p>Some contents...</p>
        <p>Some contents...</p>
        <p>Some contents...</p>
        <Form>
          <Form.Item>
            <Input ref={myRef} />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
}

ReactDOM.render(<App />, document.getElementById('container'));