我正在尝试使用React Portal将我的React应用程序实例化到一个新窗口中,但是我用来将样式从父窗口复制到新窗口中的功能无法在IE / Edge中运行。这会严重降低浏览器的速度,然后崩溃。它将在崩溃前尝试工作约3-4分钟。因此,我目前没有将任何样式导入IE / Edge中的新窗口-Chrome和FireFox可以正常工作。有人知道如何使本地CSS进入新窗口吗?
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
function copyStyles(sourceDoc, targetDoc) {
Array.from(sourceDoc.styleSheets).forEach(styleSheet => {
try {
if (styleSheet.cssRules) {
const newStyleEl = sourceDoc.createElement('style');
Array.from(styleSheet.cssRules).forEach(cssRule => {
newStyleEl.appendChild(sourceDoc.createTextNode(cssRule.cssText));
});
targetDoc.head.appendChild(newStyleEl);
} else {
const newLinkEl = sourceDoc.createElement('link');
newLinkEl.rel = 'stylesheet';
newLinkEl.href = styleSheet.href;
targetDoc.head.appendChild(newLinkEl);
}
} catch (e) {
// console.log(e);
}
});
}
export default class Portal extends React.PureComponent {
static propTypes = {
closeWindowPortal: PropTypes.func,
browser: PropTypes.string,
};
static defaultProps = {
closeWindowPortal: () => null,
browser: '',
};
constructor(props) {
super(props);
this.childWindow = window.open('', '_blank', 'width=1400, height=490');
this.containerEl =
this.props.browser === 'IE' || this.props.browser === 'Edge'
? this.childWindow.document.body.appendChild(
this.childWindow.document.createElement('div')
)
: document.createElement('div');
}
componentDidMount() {
const { browser } = this.props;
if (browser !== 'IE' || browser !== 'Edge') {
this.childWindow.document.body.appendChild(this.containerEl);
// apply css to the new window by calling function at top of file
copyStyles(document, this.childWindow.document);
} else {
this.childWindow.document.body.div.appendChild(this.containerEl);
}
this.childWindow.document.title = 'EarthCam Share';
this.childWindow.addEventListener('beforeunload', () => {
this.props.closeWindowPortal();
});
}
componentWillUnmount() {
this.childWindow.close();
this.childWindow.removeEventListener('beforeunload', () => {
this.props.closeWindowPortal();
});
}
render() {
return ReactDOM.createPortal(this.props.children, this.containerEl); //eslint-disable-line
}
}
答案 0 :(得分:0)
我必须将css附加到创建的div元素上,然后它才能起作用
copyStyles(document, this.externalWindow.document);
//this part got css working in chrome and firefox
this.containerEl.className='class1 class2';
由于无法让IE 11使用react-portal代码,我不得不完全放弃这条路线。