javascript – “警告:react-modal:未定义App元素.请使用`Modal.setAppElement(el)`或设置`appElement = {el}`“

前端之家收集整理的这篇文章主要介绍了javascript – “警告:react-modal:未定义App元素.请使用`Modal.setAppElement(el)`或设置`appElement = {el}`“前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何使用react-modal包在React应用程序的控制台中修复此警​​告:

Warning: react-modal: App element is not defined. Please use Modal.setAppElement(el) or set 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 Warning: react-modal: App element is not defined. Please use Modal.setAppElement(el) or set appElement={el}. This is needed so screen readers don’t see main content when modal is opened. It is not recommended,but you can opt-out by setting ariaHideApp={false}.

react-modal docs所有我能找到的是以下内容

App Element
The app element allows you to specify the portion of your app that should be hidden (via aria-hidden) to prevent assistive technologies such as screenreaders from reading content outside of the content of your modal.

If you are doing server-side rendering,you should use this property.

It can be specified in the following ways:

DOMElement
Modal.setAppElement(appElement);
query selector - uses the first element found if you pass in a class.
Modal.setAppElement('#your-app-element');

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

以下是我尝试添加到我的Modal组件中的一些属性变体:

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

我也试过调用Modal.setAppElement(‘root’);从src / index.js里面,其中root是我的App组件注入的根元素,index.js就是我这样做的地方.

解决方法

一些解决方案在 react-modal issue #133:中给出

The problem lies here:
取决于它何时评估react-modal@1.6.5:/lib/helpers/ariaAppHider.js#L1:

> document.body尚不存在,它将解析为undefined ||空值.
>如果使用null调用Modal.setAppElement()或者根本不使用< script />调用它放在< head />上(与上述相同).
>如果使用与任何结果不匹配的选择器调用,也可能发生这种情况.

解决方案:

浏览器渲染:

@yachaka snippet通过在放置< Modal />之前定义元素来防止此行为:

componentWillMount() {
    Modal.setAppElement('body');
}

@ungoldman answer,如果你不想依赖’setAppElement’:

Inject the bundled application JS into <body> instead of <head>.
Though ideally react-modal should wait until the DOM is loaded to try attaching to document.body.

服务器端:

If rendering on server-side,you must provide a document.body,before requiring the modal script (perhaps it should be preferable to use setAppElement() in this case).

更新:
react docs已更新,包含上述信息,因此对于遇到此问题的用户,现在应该更清楚了.
react-modal issue #567:将信息(从上面链接的问题#133)添加到文档中.

原文链接:https://www.f2er.com/js/156030.html

猜你在找的JavaScript相关文章