1

我们有 2 个大型现有网站,我们需要在它们之间共享 UI 组件。计划是这些组件是延迟加载的,并且可以根据需要通过为道具编写带有数据属性的 div 标签来经常安装在页面中的任何位置,例如

<div data-component="InfoNotification" data-title="Example InfoNotification">
    <p>With child elements</p>
</div> 

所以上面的这个 HTML 应该挂载一个 InfoNotification 组件到页面并传递props.title“示例通知”props.children<p>With child elements</p>

除了子节点props.children由于某种原因没有通过之外,这有效。

延迟加载逻辑:

import AL from './AsyncLoadable'
asyncComponents.InfoNotification = AL({loader: () => import('./lib/notifications/InfoNotification.jsx')})

组件安装代码:

import { asyncComponents } from './registeredAsyncComponents'

// Find any react mounting points on the page and load the correct component for them
const mountPoints = document.querySelectorAll('div[data-component],span[data-component]')
for (let i = 0; i < mountPoints.length; i++) {
    if (asyncComponents[mountPoints[i].dataset.component]) {
        let children = mountPoints[i].childNodes; // <-- if this was a react element it would work
        let loadableComponent = React.createElement(asyncComponents[mountPoints[i].dataset.component], mountPoints[i].dataset, children)
        ReactDOM.render(
            <I18nextProvider i18n={i18n}>
                {loadableComponent}
            </I18nextProvider>,
            mountPoints[i]
        )
    } else {
        console.error(`Unable to find a registered component named ${mountPoints[i].dataset.component}. Please register async components in src/registeredAsyncComponents.js`)
    }
}

InfoNotification 组件通过 react 正常工作,只是在尝试将 DOM 节点传递到 react children 属性时无法正常工作。

注意:我们有企业客户,需要IE11兼容的解决方案

4

0 回答 0