我正试图createPortal
小。我尝试将其渲染为:
{ () => createPortal(<PrivacyContent />, document.getElementById('privacy')) }
还有
{ createPortal(<PrivacyContent />, document.getElementById('privacy')) }
但是它们都不加载任何东西。
加载它的唯一方法是进入<PrivacyContent>
组件,并使其返回createPortal
,如下所示:
class PrivacyContent extends React.Component {
render() {
return createPortal(
<React.Fragment>
<button>Click me</button>
</React.Fragment>,
document.getElementById('privacy')
)
}
}
我希望不要在内容中使用createPortal
,而是像这样在父级执行此操作,以了解为什么它不起作用的任何想法:
import React, { lazy, Suspense } from 'react';
import { createPortal, render } from 'react-dom';
const PrivacyContent = lazy(() => import('./pages/legal/PrivacyContent'))
class App extends React.Component {
render() {
return (
<div>
{ this.testIfPathname('/legal/privacy') &&
<Suspense fallback={<div>Loading...</div>}>
{ () => createPortal(<PrivacyContent />, document.getElementById('privacy')) }
</Suspense>
}
</div>
)
}
testIfPathname(pathname) {
return window.location.pathname.toLowerCase() === pathname;
}
}
render(<App />, document.getElementById('react'));