admin管理员组

文章数量:1410737

I use Antd. I have Modal Window which consist Form. I want to focus in Input Field when user open the modal widnow. How i can do it in functional ponent? I try this but in not work for me:


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>
  );
};

I use Antd. I have Modal Window which consist Form. I want to focus in Input Field when user open the modal widnow. How i can do it in functional ponent? I try this but in not work for me:


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>
  );
};
Share Improve this question asked Aug 14, 2020 at 8:08 Утка ОбычнаяУтка Обычная 951 gold badge2 silver badges11 bronze badges 1
  • You can refer this answer for your question: stackoverflow./a/71736082/14219692 – user14219692 Commented Apr 4, 2022 at 11:40
Add a ment  | 

2 Answers 2

Reset to default 2

try this way. good luck ;)

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'));

You can actually acplish this without using any refs at all.

First, put the autoFocus prop on your Input.

<Input autoFocus name='nameWidget' ref={nameInput} onChange={handleChangeName} placeholder='Введите новое название' />

This alone will not work yet as Ant Design renders modal dialogs outside of your application's root DOM element which trips up React's handling of autoFocus. If the root element is

<div id="app"></div>

as is customary, you need to tell Ant to render the Modal into this element by using the getContainer prop:

<Modal
  getContainer={document.getElementById('app')}
  // ...
>

本文标签: javascriptReact AutoFocus on Input field inside ModalStack Overflow