Отправка фокуса в раскрывающееся меню после закрытия модального окна в React - PullRequest
1 голос
/ 06 апреля 2019
We have a requirement, where focus needs to be set on dropdown (not the child elements of dropdown) once the Modal is closed.

We are using ReactModal component, it has prop called 'shouldReturnFocusAfterClose'(when set to true) which will set focus back on button (where focus was set before modal opened) once Modal is closed.

<ReactModal
      isOpen={isOpen}
      shouldCloseOnOverlayClick={shouldCloseOnOverlayClick}
      onRequestClose={onRequestClose}
      getAppElement={getAppElement}
      closeTimeoutMS={200}
      contentRef={contentRef}
      shouldReturnFocusAfterClose={true} >
</ReactModal> 

Выше приведен код, ReactModal устанавливает фокус, как и ожидалось (устанавливает фокус на кнопку там, где она была до открытия модального режима)

*** ReactModal is setting focus as expected (setting focus on button where it was before modal is opened)

*** Once clicked(key event) on the one of the options of dropdown, Modal is opened. Our requirement is...Once it is closed, focus should be set to dropdown button instead of options of dropdown.

1 Ответ

0 голосов
/ 06 апреля 2019

хорошо, так что давайте попробуем использовать наш собственный способ.

Позволяет установить ссылку на ваш select компонент. А на onRequestClose давайте сосредоточимся на этом.

class YourComponent extends React.Component {
    refSelect = React.createRef();

    openPopup = () => {
      this.setState({ isOpen: true });
    }

    onRequestClose = () => {
      this.setState({ isOpen: false });
      this.refSelect.focus();
    }

    render() {
      return (
        <select ref={ref => this.refSelect = ref} onClick={this.openPopup}>
          <option value="volvo">Volvo</option>
          <option value="saab">Saab</option>
        </select>
         <ReactModal 
             // your other props...
             isOpen={isOpen} 
             onRequestClose={this.onRequestClose}
             shouldReturnFocusAfterClose={false} />
      );
    }
}

...