【问题标题】:styled-components not restyling a componentstyled-components 不重新设置组件的样式
【发布时间】:2018-11-12 14:47:45
【问题描述】:

我在 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}) =&gt; &lt;Aside className={className}/&gt;;

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

如图所示

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

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

【问题讨论】:

    标签: javascript ecmascript-6 styled-components gatsby


    【解决方案1】:

    要按照您链接的示例中的方式进行操作,您需要像这样将 className 道具传递给孩子:

    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>
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-04
      • 2020-05-01
      • 2021-09-19
      • 2021-07-16
      • 2018-08-21
      • 2020-04-04
      • 2021-07-13
      • 1970-01-01
      • 2018-01-19
      相关资源
      最近更新 更多