警告:react-modal:未定义应用程序元素。请使用`Modal.setAppElement(el)`或设置`appElement = {el}`。

53

我该如何解决在React应用程序中使用react-modal包时控制台中出现的以下警告:

Warning: react-modal:未定义App元素。 请使用Modal.setAppElement(el)或设置appElement={el}

我一直无法弄清楚el应该是什么。

背景: 在我的App.js根组件文件中:

...
import Modal from 'react-modal';
...
class App extends Component {
  ...
  render(){
    ...  
    <Modal
      className="modal"
      overlayClassName="overlay"
      isOpen={foodModalOpen}
      onRequestClose={this.closeFoodModal}
      contentLabel="Modal"
    >
    ...
  }
}

其中...表示未显示的代码。

一切都运行良好,但当模态框打开时,我的控制台会出现以下警告:

index.js:2177 警告:react-modal:未定义应用程序元素。请使用Modal.setAppElement(el)或设置appElement={el}。这是必需的,以便屏幕阅读器在打开模态框时不会看到主内容。虽然不建议,但您可以通过设置ariaHideApp={false}来选择退出。

react-modal文档中,我能找到的仅有以下内容:

应用程序元素
应用程序元素允许您指定应该隐藏的应用程序部分(通过aria-hidden),以防止辅助技术(如屏幕阅读器)阅读模态框内容之外的内容。

如果您正在进行服务器端渲染,则应使用此属性。

它可以通过以下方式指定:

DOM元素
Modal.setAppElement(appElement);
查询选择器-如果传入类,则使用找到的第一个元素。
Modal.setAppElement('#your-app-element');

不幸的是,这没有帮助!我无法弄清楚el应该表示什么。

以下是我尝试添加到我的模态框组件中的许多属性变化:

`appElement={el}`,  
`appElement="root"` where `root` is the id that my App component is injected into   
`appElement={'root'}`   
`appElement="div"`,   
`appElement={<div>}`,   
`appElement={"div"}`  

我还尝试过在src/index.js中调用Modal.setAppElement('root');,其中root是我的App组件注入的根元素,而index.js是我这样做的地方。


1
Sheryl的回答是正确的 - 但是为了让你知道,“el”通常指的是引用,是“element”的缩写。 - Wills Manley
13个回答

1
如果在使用“react-testing-library”进行测试时遇到了该警告,请参考以下解决方案: https://github.com/reactjs/react-modal/issues/576#issuecomment-524644035 使用 react-testing-library (https://testing-library.com/),我用以下方法摆脱了这个警告:
import Modal from "react-modal";

const { container } = render(<MyComponent />);
Modal.setAppElement(container);

....  // to the testing, use Modal

或者,如果您想直接测试模态组件:
const { container, rerender } render(<MyModalComponent isOpen={false} />);
Modal.setAppElement(container);
// now the appElement is set we can show the modal component
rerender(<MyModalComponent isOpen={false} />);

....  // to the testing

0
在Next.js中解决: 这对我来说解决了问题,我只是在布局的根body中添加了一个id,然后在模态框中加入appElement={document.getElementById("root")}layout.js组件
<body suppressHydrationWarning={true} id='root'>
     <div className='main-container col-12 d-flex flex-row h-100 w-100 col-12 justify-content-start align-items-start'>
          <main className='col-10'>{children}</main>
     </div>
</body>

一些组件
<Modal
        isOpen={modalIsOpen}
        onRequestClose={closeModal}
        contentLabel='Book Modal'
        appElement={document.getElementById("root")}
        style={{
          content: {
            width: "850px",
            height: "85vh",
            margin: "auto",
            padding: "0px",
            border: "none",
            overflow: "hidden",
          },
        }}
      >
      <h1>Content Of Modal Goes Here</h1>
</Modal>

-3

删除这个属性 className="modal" 然后再次运行


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接