代码之家  ›  专栏  ›  技术社区  ›  Noitidart

createPortal作为子函数不工作

  •  0
  • Noitidart  · 技术社区  · 7 年前

    我正在努力 createPortal

    { () => createPortal(<PrivacyContent />, document.getElementById('privacy')) }
    

    { createPortal(<PrivacyContent />, document.getElementById('privacy')) }
    

    但是,它们都没有加载任何内容。

    让它加载的唯一方法是进入 <PrivacyContent> 组件并使其返回 这样地:

    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'));
    
    0 回复  |  直到 7 年前