简体   繁体   English

样式化组件不包装另一个样式化组件

[英]Styled component not wrapping another styled component

I have a Popup component like so:我有一个像这样的Popup组件:

import React, { useEffect } from 'react';
import styled from 'styled-components';

const Div = styled.div`
  position: absolute;
`;

const Popup = ({ isOpen, onClose, children }) => {

  useEffect(() => {
    const onClick = e => {
      if (isOpen && onClose) {
        onClose();
      }
    };

    document.addEventListener('click', onClick);
    return () => document.removeEventListener('click', onClick);
  }, [isOpen, onClose]);

  return <Div>
    {isOpen && children}
  </Div>;
};

export default Popup;

Now I'm trying to wrap it into another styled component:现在我试图将它包装到另一个样式组件中:

const Menu = styled(Popup)`
  background-color: red;
`;

But using this Menu only applies the styles from the Popup , ie the background color stays white.但使用此Menu仅适用于Popup中的 styles,即背景颜色保持白色。 Why isn't it changing to red?为什么不变成红色?

You need to add className prop to Popup component in order to allow the css-in-js library ( styled-component ) to inject its styles:您需要将className属性添加到Popup组件,以允许 css-in-js 库( styled-component )注入其 styles:

const Popup = ({ isOpen, onClose, children, className }) => {
  //...
  return <Div className={className}>{isOpen && children}</Div>;
};

See Styling normal React components in Docs .请参阅在Docs设置普通 React 组件的样式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM