我正在使用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组件的引用,以便在需要时轻松卸载它?
答案 0 :(得分:0)
您将this.element
设置为ReactDOM.render的结果,这是错误的。只需将mount
课程中的ComponentMounter
功能更改为以下内容即可解决您的问题:
mount = (element) => {
this.element = element;
ReactDOM.render(this.component, this.element);
}
这是因为您希望在父DOM节点上调用unmountComponentAtNode
,之前您将this.element
设置为ReactDOM.render
的返回值,返回对您挂载的组件的引用(或null)而不是安装组件的dom节点。