javascript “警告:react-modal:App 元素未定义。请使用`Modal.setAppElement(el)` 或设置`appElement={el}`”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48269381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"Warning: react-modal: App element is not defined. Please use `Modal.setAppElement(el)` or set `appElement={el}`"
提问by SherylHohman
How to fix this warning in console of a React app using the react-modal package:
如何使用 react-modal 包在 React 应用程序的控制台中修复此警告:
Warning: react-modal: App element is not defined. Please use
Modal.setAppElement(el)or setappElement={el}
警告:react-modal:App 元素未定义。请使用
Modal.setAppElement(el)或设置appElement={el}
I have not been successful at figuring out what elis supposed to be.
我没有成功地弄清楚el应该是什么。
Context: in my App.js root component file:
上下文:在我的 App.js 根组件文件中:
...
import Modal from 'react-modal';
...
class App extends Component {
...
render(){
...
<Modal
className="modal"
overlayClassName="overlay"
isOpen={foodModalOpen}
onRequestClose={this.closeFoodModal}
contentLabel="Modal"
>
...
}
}
Where ...indicates code not shown.
其中...表示代码未显示。
Everything works fine, but when the Modal is opened, the following Warning appears in my console:
一切正常,但是当打开 Modal 时,控制台中会出现以下警告:
index.js:2177 Warning: react-modal: App element is not defined. Please use
Modal.setAppElement(el)or setappElement={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 settingariaHideApp={false}.
index.js:2177 警告:react-modal:App 元素未定义。请使用
Modal.setAppElement(el)或设置appElement={el}。这是必需的,因此屏幕阅读器在打开模态时看不到主要内容。不建议这样做,但您可以通过设置选择退出ariaHideApp={false}。
In the react-modal docsall I can find is the following:
在react-modal 文档中,我只能找到以下内容:
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');
App 元素 app 元素允许您指定应隐藏的应用程序部分(通过 aria-hidden),以防止屏幕阅读器等辅助技术读取模态内容之外的内容。
如果您正在进行服务器端渲染,则应使用此属性。
可以通过以下方式指定:
DOM元素
Modal.setAppElement(appElement);query selector - uses the first element found if you pass in a class.Modal.setAppElement('#your-app-element');
Unfortunately, this has not helped !
I cannot figure out what elis supposed to represent.
不幸的是,这没有帮助!我无法弄清楚el应该代表什么。
Here are some of the many property variations I have tried adding to my Modal component:
以下是我尝试添加到我的 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"}`
I've also tried calling Modal.setAppElement('root');from inside src/index.js, where rootis the root element that my Appcomponent is injected into, and index.js is where I do that.
我也打过电话Modal.setAppElement('root');,从里面src/index.js,那里root是根元素,我的App分量被注入,并index.js是我做的。
回答by SherylHohman
Some solutions are given in react-modal issue #133:
react-modal issue #133中给出了一些解决方案:
The problem lies here:Depending on when it evaluates [email protected]:/lib/helpers/ariaAppHider.js#L1:
问题出在这里:取决于它何时评估 [email protected]:/lib/helpers/ariaAppHider.js#L1:
- document.body does not exist yet and it will resolve to
undefined || null. - if
Modal.setAppElement()is called withnullor not called at all with the<script />placed on<head />(same as above). - Probably it can also happen if called with a
selectorthat does not match any results.
- document.body 尚不存在,它将解析为
undefined || null. - 如果
Modal.setAppElement()被调用null或根本不调用被<script />放置<head />(同上)。 - 如果使用
selector与任何结果都不匹配的a进行调用,也可能会发生这种情况。
Solutions:
解决方案:
Browser Rendering:
浏览器渲染:
@yachaka snippetprevents this behavior by defining the element before placing the <Modal />:
@yachaka 片段通过在放置之前定义元素来防止这种行为<Modal />:
componentWillMount() {
Modal.setAppElement('body');
}
@ungoldman answer, if you don't want to depend on `setAppElement':
@ungoldman 回答,如果你不想依赖`setAppElement':
Inject the bundled application JS into
<body>instead of<head>.
Though ideallyreact-modalshould wait until the DOM is loaded to try attaching todocument.body.
将捆绑的应用程序 JS 注入
<body>而不是<head>.
虽然理想情况下react-modal应该等到 DOM 加载后尝试附加到document.body.
server-side:
服务器端:
If rendering on server-side, you must provide a
document.body, before requiring the modal script (perhaps it should be preferable to usesetAppElement()in this case).
如果在服务器端渲染,则必须
document.body在需要模式脚本之前提供, (也许setAppElement()在这种情况下最好使用)。
Update:
react docshave been updated to include the information above, so they should now be clearer for users running into this issue.
react-modal issue #567:add information (from issue #133 linked above) to the docs.
更新:
react 文档已更新以包含上述信息,因此对于遇到此问题的用户来说,它们现在应该更清晰。
react-modal 问题 #567:将信息(来自上面链接的问题 #133)添加到文档中。
回答by amrit chhetri
Add ariaHideApp={false}to Modalattributes.
添加 ariaHideApp={false}到Modal属性。
This should work:
这应该有效:
<Modal isOpen={!!props.selectedOption}
onRequestClose={props.clearSelectedOption}
ariaHideApp={false}
contentLabel="Selected Option"
>
</Modal>
回答by Aditya Mishra
Just include appElement={document.getElementById('app')}inside your modal like this
只需appElement={document.getElementById('app')}像这样包含在您的模态中
<Modal
className="modal"
appElement={document.getElementById('app')}
>
It will work 100% if app is your central in index.html from where react loads.
如果 app 是你在 index.html 中反应加载的中心,它将 100% 工作。
回答by JoeTidee
If getting the Warning: react-modal: App element is not defined...error when running tests (we were running Jest), you can suppress the warnings by adding the following to your test file:
如果Warning: react-modal: App element is not defined...在运行测试时出现错误(我们正在运行 Jest),您可以通过将以下内容添加到您的测试文件中来抑制警告:
import ReactModal from 'react-modal';
ReactModal.setAppElement('*'); // suppresses modal-related test warnings.
回答by Nathaniel Hill
For reference, since it was a pain for me, if you are doing SSR, use the following code to prevent errors server-side:
仅供参考,因为对我来说很痛苦,如果你在做SSR,使用下面的代码来防止服务器端出错:
if (typeof(window) !== 'undefined') {
ReactModal.setAppElement('body')
}
You could put this in componentDidMount()anywhere you use a modal or I put it in a custom modal component so it's nice and DRY.
你可以把它放在componentDidMount()任何你使用模态的地方,或者我把它放在一个自定义的模态组件中,所以它很好而且很干。
回答by Reinhard
If you get that warning on testing with the "react-testing-library" here is a solution: https://github.com/reactjs/react-modal/issues/576#issuecomment-524644035
如果您在使用“react-testing-library”进行测试时收到警告,这里是一个解决方案:https: //github.com/reactjs/react-modal/issues/576#issuecomment-524644035
using the react-testing-library (https://testing-library.com/) I get rid of that warning with:
使用 react-testing-library ( https://testing-library.com/) 我摆脱了警告:
import Modal from "react-modal";
const { container } = render(<MyComponent />);
Modal.setAppElement(container);
.... // to the testing, use Modal
or, if you want to test the modal component directly:
或者,如果您想直接测试模态组件:
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
回答by Marat Hakobjanyan
The shortest solution is to add
appElement={document.getElementById("hereIsYourRootElementId")}It lets react-modal know where is your root element. It is not required, but recommended.
最短的解决方案是添加
appElement={document.getElementById("hereIsYourRootElementId")}它让 react-modal 知道你的根元素在哪里。它不是必需的,但建议使用。
回答by Mo Hemati
you need to add # before your root element id.
您需要在根元素 id 之前添加 #。
import React from 'react';
import Modal from 'react-modal';
Modal.setAppElement('#root');
const OptionModal = (props) => (
<Modal
isOpen={!!props.selectedOption}
contentLabel='this is the selected option'
>
<h3>Selected Option</h3>
{props.selectedOption && <p>{props.selectedOption}</p>}
<button onClick = {props.handleCloseOptionModal}>Close</button>
</Modal>
);
export default OptionModal;
here is the reference: http://reactcommunity.org/react-modal/accessibility/
回答by Beau Smith
This is my TypeScript Modalcomponent which wraps react-modalv3.8.1:
这是我的 TypeScriptModal组件,它封装了react-modalv3.8.1:
import React from 'react'
import ReactModal from 'react-modal'
interface Props {
isOpen: boolean
ariaLabel?: string
}
const Modal: React.FC<Props> = ({
children,
ariaLabel = 'Alert Modal',
isOpen,
}) => (
<ReactModal
appElement={document.getElementById('root') as HTMLElement}
ariaHideApp={process.env.NODE_ENV !== 'test'}
isOpen={isOpen}
contentLabel={ariaLabel}
testId="modal-content"
>
{children}
</ReactModal>
)
export default Modal
Usage in component with state = { isOpen: true }:
在组件中使用state = { isOpen: true }:
<Modal isOpen={this.state.isOpen}>
<p>
Modal Content here…
</p>
<button onClick={() => { this.setState({ isOpen: false }) }}>Okay</button>
</Modal>

