我正在使用 webpack 在非反应应用程序中使用反应组件。想法是以某种方式导出它们,以便它们可以在任何 DOM 上安装和卸载。
这是我正在测试组件的 html 页面:
<script type="text/javascript" src="<?php echo base_url('assets/javascripts/build/component.js') ?>"></script>
<button onclick="showComponent()" />show component</button>
<button onclick="hideComponent()" />hide component</button>
<div id='mainContainer'></div>
<script >
function showComponent() {
MyComponent.mount(document.getElementById('mainContainer'))
}
function hideComponent() {
MyComponent.unmount()
}
</script>
这是 webpack 入口点:
import React from 'react'
import MyComponent from '/path/to/MyComponent'
import ComponentMounter from '/path/to/ComponentMounter'
let componentMounter = new ComponentMounter(<MyComponent />)
export let mount = componentMounter.mount
export let unmount = componentMounter.unmount
在 webpack 配置中,我将包导出为库,使用:
output: {
path: './assets/javascripts/build/',
filename: 'component.js',
libraryTarget: 'var',
library: 'MyComponent'
}
ComponentMounter 类:
import ReactDOM from 'react-dom'
class ComponentMounter {
constructor(component) {
this.component = component
}
mount = (element) => {
// This renders the react 'component', mounting it in the DOM 'element'
this.element = ReactDOM.render(this.component, element)
}
unmount = () => {
// This unmounts the react 'component', removing the DOM 'element'
ReactDOM.unmountComponentAtNode(this.element)
}
}
export default ComponentMounter
希望你能看到我在那里尝试做的事情。单击显示按钮时,组件安装没有问题。
但是当我尝试卸载它时,似乎该元素不是有效的 DOM 元素,因为我收到了以下警告:
invariant.js:38 Uncaught Invariant Violation: unmountComponentAtNode(...): Target container is not a DOM element.
如何保留对安装在 ComponentMounter 对象内的 DOM 节点中的 React 组件的引用,以便在需要时轻松卸载它?