Styled Components无法包裹自定义组件?Popup样式不生效问题咨询
Problem Description
I've created this Popup component using React and styled-components:
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;
When I try to wrap it in another styled component to add custom styles:
const Menu = styled(Popup)` background-color: red; `;
The Menu component only uses the original styles from Popup—the red background doesn't show up. Why is this happening?
Solution
The core issue here is that your Popup component isn't passing the className prop generated by styled-components down to its internal styled Div element.
When you use styled(Popup), styled-components creates a new component that adds a custom className with your background-color: red rule. But your Popup doesn't accept this className prop or apply it to the root Div, so those custom styles never get attached to the actual DOM element that renders the popup.
To fix this, update your Popup component to accept and pass the className to the internal Div:
const Popup = ({ isOpen, onClose, children, className }) => { useEffect(() => { const onClick = e => { if (isOpen && onClose) { onClose(); } }; document.addEventListener('click', onClick); return () => document.removeEventListener('click', onClick); }, [isOpen, onClose]); // Pass the external className to the styled Div return <Div className={className}>{isOpen && children}</Div>; };
Now when you use Menu, the custom background-color: red style will be applied to the root Div of the Popup, and you'll see the red background as expected.
As a general rule when wrapping custom components with styled-components: always make sure your component accepts the className prop and applies it to the DOM element you want styled.
内容的提问来源于stack exchange,提问作者Mahi

