如何选择从另一个文件导入的嵌套样式组件

发布于 2025-01-25 13:24:02 字数 920 浏览 0 评论 0原文

我有以下方案:

这应该是可重复使用的组件,要在应用程序的不同部分中导入

import React from 'react';
import styled from 'styled-components';

const Wrapper = styled.div`
// some basic styling here
`

const DisplayInfo = styled.div`
//more styling
`

const Component = props => (
   <Wrapper>
       <DisplayInfo>{props.title}</DisplayInfo>
   </Wrapper>

export default Component;
);

该组件,该组件将在另一个组件中导入,并且某些造型应该被覆盖

....
import Component from './Component';

const NewWrapper = styled.div`
   //here I should select the ${Component} and overwrite some of it's css
`;

const ParentComponent = props => ({
    <NewWrapper>
      <Component title={props.title} />
    </NewWrapper>
})

我的问题,我尝试了很多策略来定位在NewWrapper样式中导入的“组件”,但没有任何作用。只有当我在第二个文件中声明“组件”时,才能起作用。 没有其他方法是因为我希望它们分开吗?

PS:还试图将“ classname”传递给第一个文件中的包装器,如样式组件文档中所述,但似乎仍然没有用。

I Have the following scenario:

This should be a reusable component to be imported in different parts of the app

import React from 'react';
import styled from 'styled-components';

const Wrapper = styled.div`
// some basic styling here
`

const DisplayInfo = styled.div`
//more styling
`

const Component = props => (
   <Wrapper>
       <DisplayInfo>{props.title}</DisplayInfo>
   </Wrapper>

export default Component;
);

That component will be imported in another component and some of it's styling should be overwritten

....
import Component from './Component';

const NewWrapper = styled.div`
   //here I should select the ${Component} and overwrite some of it's css
`;

const ParentComponent = props => ({
    <NewWrapper>
      <Component title={props.title} />
    </NewWrapper>
})

My issue that is I tried a lot of tactics to target the imported 'Component' inside the NewWrapper styling, but nothing works. Only If I declare 'Component' inside the second file does it works.
Isn't there another way because I want them to be separated?

P.S: Also tried to pass 'classname' to the Wrapper in the first file as it says in the styled-components doc, but it still didn't seem to work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

赠我空喜 2025-02-01 13:24:02

您实际上很近。当您针对样式组件中的另一个样式组件时,诸如此类:

const StyledParent = styled.div`
  ${StyledChild} {
    ...styles
  }
`;

父母期望接收样式的组件,而不是React组件。在第一个文件中更改导出,然后尝试以下操作:

export default styled(Component);

You're quite close actually. When you're targeting another Styled Component inside a Styled Component, like this:

const StyledParent = styled.div`
  ${StyledChild} {
    ...styles
  }
`;

The parent expects to receive a Styled Component, not a React component. Change your export in the first file, and try this:

export default styled(Component);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文