【问题标题】:Styled-components dynamic CSS is not generated in a new windowStyled-components 动态 CSS 不在新窗口中生成
【发布时间】:2021-01-03 13:59:06
【问题描述】:

我正在使用react-new-window 打开一个弹出窗口。弹出窗口包括一些以styled-components 为样式的动态组件(切换、下拉菜单等)。

在我尝试与其中一个动态组件交互并更改状态之前,所有内容都会正确显示(例如,我将切换开关从关闭切换到开启)。然后事实证明,通常生成并附加到<head> 的新组件状态的 CSS 类实际上附加到父窗口的 <head>,而不是弹出窗口。所以我的组件似乎失去了样式。

我在父窗口中也有相同的组件。因此,如果我在打开弹出窗口之前与它们进行交互,样式会像往常一样附加到 <head>,然后被复制到弹出窗口中,一切看起来都很好。

所以我看到了两种可能的解决方法:

  1. 我可以告诉 styled-component 以某种方式与新窗口而不是父窗口对话。
  2. 作为一种解决方法,我可以以某种方式以编程方式预先生成所有样式(数量不多)。

问题是我不确定如何做这两件事。欢迎任何想法!

【问题讨论】:

    标签: javascript css reactjs styled-components new-window


    【解决方案1】:

    选项1的解决方案实际上可以通过styled-component API:

    import React from 'react';
    import styled, {StyleSheetManager} from 'styled-components';
    import NewWindow from 'react-new-window';
    
    class Parent extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          showPopout: false,
        };
        this.nwRef = React.createRef();
      }
    
      render () {
        ... some stuff
        this.state.showPopout && (
        <StyleSheetManager target={this.nwRef.current}>
          <NewWindow
            title="Title"
            features={{width: '960px', height: '600px'}}
            onUnload={() => this.setState({showPopout: false})}
          >
            <div ref={this.nwRef}>
              <Popout isPopout={true}>
                ... popup stuff
              </Popout>
            </div>
          </NewWindow>
        </StyleSheetManager>
      )}
    }
    

    【讨论】:

      【解决方案2】:

      如果有人需要,这里有一个功能组件的工作示例

      const Parent = () => {
        const [showPopout, setShowPopout] = useState(false)
        const [newWindowNode, setNewWindowNode] = useState(null)
      
        const nwRef = useCallback(node => setNewWindowNode(node), [])
      
        return showPopout 
          ? (
            <StyleSheetManager target={newWindowNode}>
              <NewWindow
                title="Title"
                features={{width: '960px', height: '600px'}}
                onUnload={() => setShowPopout(false)}
              >
                <div ref={nwRef}>
                  <Popout isPopout={true}>
                    ... popup stuff
                  </Popout>
                </div>
              </NewWindow>
            </StyleSheetManager>
          ) : null
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-06
        • 2019-12-22
        • 1970-01-01
        • 2022-08-06
        • 2023-03-24
        • 2021-06-27
        • 2021-02-19
        • 1970-01-01
        相关资源
        最近更新 更多