我有一个React应用程序,在这里我要打开一个新的浏览器选项卡点击。问题是我的样式组件的样式不会加载在这个新的浏览器选项卡中。
为什么我的样式组件的样式没有加载在新的浏览器选项卡中?
这是我的浏览器选项卡组件:
import { useState, useRef, useEffect } from 'react'
import { createPortal } from 'react-dom'
export const NewBrowserTab = ({ children }) => {
const [container, setContainer] = useState(null)
const newWindow = useRef(null)
useEffect(() => {
setContainer(document.createElement('div'))
}, [])
useEffect(() => {
if (container) {
newWindow.current = window.open('', '')
newWindow.current.document.body.appendChild(container)
return () => {
newWindow.current.close()
}
}
}, [container])
return container && createPortal(children, container)
}
这就是我使用这个组件的地方:
import React, { useState } from 'react'
import { NewBrowserTab } from '@components/NewBrowserTab/NewBrowserTab'
import styled from 'styled-components'
const DownloadButton = () => {
const [isActive, setIsActive] = useState(false)
return (
<>
<button onClick={() => setIsActive(true)}>open window</button>
{isActive &&
<NewBrowserTab>
<MyStyledComponent>this is supposed to be red in new window!</MyStyledComponent>
</NewBrowserTab>}
</>
)
}
const MyStyledComponent = styled.div`
color: red;
background-color: blue;
`
export default DownloadButton
在这里,您可以看到devtools中没有样式(没有红色或蓝色):
发布于 2021-09-17 03:07:33
@Quentin,谢谢你的帮助。我也会发布这个答案来详细回答我的问题(如果将来有人会碰到这个问题的话):
当我在"NewBrowserTab"-component中使用直接DOM操作时,样式组件不会加载到新选项卡中。
因此,我所做的是使用这个页面组件添加一个新的路由:
import React, { FC } from 'react'
import Flex from '@components/containers/Flex'
import styled from 'styled-components'
export const DocumentPage: FC = () => {
return (
<Flex direction='column'>
<MyStyledComponent>123</MyStyledComponent>
</Flex>
)
}
const MyStyledComponent = styled.div`
color: red;
background-color: blue;
`
export default DocumentPage
并在一个新的选项卡中使用React路由器打开它:
import React from 'react'
import { Link } from 'react-router-dom'
const DownloadButton = () => {
return (
<>
<Link to="dokument" target="_blank" rel="noopener noreferrer">
new tab with styled component
</Link>
</>
)
}
export default DownloadButton
这意味着我可以摆脱NewBrowserTab组件,在我的应用程序中导航的地方,窗口仍然是打开的,因为它不再是一个可以卸载的组件!
发布于 2021-09-17 01:45:04
样式化组件通过生成一个<style>
元素来工作,该元素包含一些规则集,这些规则集通过类名应用于从组件生成的元素。
您要将带有类名的元素复制到新窗口,而不是<style>
元素。
通常,我会使用React路由器来处理这个问题,并将新窗口指向URL,该URL传递您希望通过URL显示的数据。
https://stackoverflow.com/questions/69221183
复制相似问题