styled-components 不重新设计组件

styled-components not restyling a component

我遇到了一些问题 're-styling' Gatsby 中的组件使用 styled-components

"styled-components": "^3.3.0" "gatsby-plugin-styled-components": "^2.0.11"

我的 gatsby-config 中有 gatsby-plugin-styled-components,当我再次通过 styled() 放置自定义组件时,样式适用于所有栏,例如:

我在此处设置了侧边栏样式

import React, { Component } from "react";
import styled from "styled-components";

class Aside extends Component {
  render() {
    return (
      <Sidebar>
        <List>
          <Item>Pintrest 1</Item>
          <Item>Pintrest 2</Item>
          <Item>Pintrest 3</Item>
        </List>
      </Sidebar>
    );
  }
}

const Sidebar = styled.div`
  position: absolute;
  width: 200px;
  left: calc(100% + 20px);

  @media (max-width: 1200px) {
    position: relative;
    width: 100%;
    left: 0;
    top: 0;
  }
`;

在一页上我想要样式 top: 0; 所以我通过

const SideBar = styled(Aside)`
  top: 0;
`;

.

import React from 'react'
import Helmet from 'react-helmet'
import Link from 'gatsby-link'
import get from 'lodash/get'
import styled from "styled-components";

import Bio from '../components/Bio'
import Aside from '../components/Aside';

class BlogPostTemplate extends React.Component {
  render() {
    const post = this.props.data.markdownRemark
    const siteTitle = get(this.props, 'data.site.siteMetadata.title')
    const { previous, next } = this.props.pathContext

    return (
      <div>
        <Helmet title={`${post.frontmatter.title} | ${siteTitle}`} />
        <Bio />
        <Post>
          <h1>{post.frontmatter.title}</h1>
          <SideBar/>
        </Post>
      </div>
    )
  }
}

甚至尝试过

const aside = ({className}) => <Aside className={className}/>;

const SideBar = styled(aside)`
  top: 0;
`;

如图所示

https://www.styled-components.com/docs/basics#styling-any-components

但它不起作用并且没有改变样式这是库 gatsby-plugin-styled-components 或样式组件的限制还是我误解了 styled-components

的目的

要按照您链接的示例中的方式进行操作,您需要将 className 道具传递给 child,如下所示:

class Aside extends Component {
  render() {
    return (
      <Sidebar className={this.props.className}>
        <List>
          <Item>Pintrest 1</Item>
          <Item>Pintrest 2</Item>
          <Item>Pintrest 3</Item>
        </List>
      </Sidebar>
    );
  }
}