React 中使用样式组件的样式子组件不起作用

问题描述 投票:0回答:1

我正在深入研究 React,并且一直在尝试使用样式化组件的 Modal 组件。我正在尝试实现与 Framer Motion 的

motion.div
类似的效果,但使用样式组件。

到目前为止,我的基本结构运行良好:

"use client"

export default function Modal({ children }: { children?: ReactNode }) {
  return <ModalStyled>{children}</ModalStyled>
}

Modal.Item = function ({ children }: { children?: ReactNode }) {
  return (
    <ModalItemStyled>
      {children}
    </ModalItemStyled>
  )
}

它做得很好!但是,当我尝试使用样式组件自定义样式时,如下所示:

export const CustomModalItem = styled(Modal.Item)`
  background-color: red;
`

看起来样式没有被应用。 😕 我很确定我在实施过程中遗漏了一些东西。任何建议或指导将非常感激!另外,我愿意接受任何使代码变得更好的技巧。非常感谢您的帮助! 🙌

"dependencies": {
  "next": "latest",
  "react": "^18",
  "react-dom": "^18",
  "styled-components": "^6.1.1"
}
javascript css reactjs next.js styled-components
1个回答
0
投票

默认情况下,样式组件不适用于复合组件。您在

CustomModalItem
中定义的样式不会直接应用于
Modal.Item
组件。

为了达到所需的结果,您可以将样式作为 props 传递给您的

Modal.Item
组件,并将它们应用到其自己的样式组件中。这是一个例子:

import styled from 'styled-components';
import { ReactNode } from 'react';

const ModalStyled = styled.div`
  /* Your Modal styles here */
`;

const ModalItemStyled = styled.div`
  /* Your default Modal.Item styles here */

  /* You can add additional styles based on props */
  background-color: ${(props) => (props.customBackground ? 'red' : 'transparent')};
`;

export const Modal = ({ children }: { children?: ReactNode }) => {
  return <ModalStyled>{children}</ModalStyled>;
};

Modal.Item = function ({ children, ...props }: { children?: ReactNode; customBackground?: boolean }) {
  return <ModalItemStyled customBackground={props.customBackground}>{children}</ModalItemStyled>;
};

export const CustomModalItem = styled(Modal.Item)`
  /* Additional styles specific to CustomModalItem */
`;

在上面的示例中,ModalItemStyled 组件接受一个名为

customBackground
的 prop,并根据该 prop 设置背景颜色。这样,您就可以在使用
CustomModalItem
时传递 customBackground 属性。

您可以这样使用它:

import { Modal, CustomModalItem } from 'your-path';

const MyComponent = () => {
  return (
    <Modal>
      <Modal.Item>Default Modal Item</Modal.Item>
      <CustomModalItem customBackground>Custom Modal Item with Red Background</CustomModalItem>
    </Modal>
  );
};
© www.soinside.com 2019 - 2024. All rights reserved.