1
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.
4

1 回答 1

0

好的,让我们尝试使用我们的自定义方式。

让我们将 ref 设置为您的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} />
      );
    }
}

于 2019-04-06T12:51:57.250 回答