react正常無(wú)法在父組件dom節(jié)點(diǎn)之外的其他節(jié)點(diǎn)創(chuàng)建組件概页,查文檔發(fā)現(xiàn)react提供了Portals方法來(lái)實(shí)現(xiàn):
Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.
文檔地址:傳送門
示例代碼:
import React from 'react'
import ReactDOM from 'react-dom'
export default class Layer extends React.Component {
constructor(props) {
super(props);
this.el = document.createElement('div');
this.el.setAttribute('class', 'layer');
}
componentDidMount() {
document.body.appendChild(this.el);
}
componentWillUnmount() {
document.body.removeChild(this.el);
}
render() {
return ReactDOM.createPortal((
<div className="content">
layer
</div>
), this.el);
}
}