繁体   English   中英

React Gatsbyjs-通过样式组件传递道具

[英]React Gatsbyjs - Passing props with styled components

我在带有样式化组件的GatsbyJS项目中遇到问题。 我将一个道具传递给ContentBlock组件,然后将其传递给样式化的StyledContentBlock组件,该组件应根据道具的值进行调整。

但是,这不起作用。 CSS永不更改,将fullWidth设置为true无效。

ContentBlock组件:

import PropTypes from "prop-types"
import React from "react"
import styled from "styled-components"
import device from "../shared/devices"
import H2 from "./h2"

const StyledContentBlock = styled.div`
  @media ${device.mobile} {
    grid-column-start: 1;
    grid-column-end: 3;
  }

  @media ${device.tablet} {
    grid-column-start: 1;
    grid-column-end: ${props => props.fullWidth ? 7 : 4};
  }
`

const ContentBlockHeading = styled(H2)`
  @media ${device.mobile} {
    margin-bottom: 20px;
  }

  @media ${device.tablet} {
    margin-bottom: 20px;
  }

  @media ${device.desktop} {
    margin-bottom: 22px;
  }
`

const ContentBlock = ({ title, fullWidth, children }) => (
  <StyledContentBlock>
    <ContentBlockHeading>{title}</ContentBlockHeading>
    {children}
  </StyledContentBlock>
);

ContentBlock.propTypes = {
  title: PropTypes.string,
  fullWidth: PropTypes.bool,
  children: PropTypes.node.isRequired,
}

ContentBlock.defaultProps = {
  title: '',
  fullWidth: false,
}

export default ContentBlock

在页面上使用它:

import React from "react"

import Layout from "../components/layout"
import ContentBlock from "../components/content-block"

const IndexPage = () => (
  <Layout>
    <ContentBlock title="Some title">
    </ContentBlock>
    <ContentBlock title="Some other title" fullWidth>
    </ContentBlock>
  </Layout>
)

export default IndexPage

我很机智。 这里发生了什么? 我还尝试了不使用模式匹配并直接访问props对象。 无效:

const ContentBlock = (props) => (
  // etc

尝试将道具传递给样式化的组件

const ContentBlock = (props) => (
  <StyledContentBlock {...props}>
    <ContentBlockHeading>{props.title}</ContentBlockHeading>
    {props.children}
  </StyledContentBlock>
);

或通过破坏

const ContentBlock = ({ title, fullWidth, children }) => (
  <StyledContentBlock fullWidth={fullWidth}>
    <ContentBlockHeading>{title}</ContentBlockHeading>
    {children}
  </StyledContentBlock>
);

您不会将任何道具传递给StyledContentBlock ,请尝试以下操作:

const ContentBlock = ({ title, fullWidth, children }) => (
  <StyledContentBlock fullWidth={fullWidth}>
    <ContentBlockHeading>{title}</ContentBlockHeading>
    {children}
  </StyledContentBlock>
);

如在文档中所示: https : //www.styled-components.com/docs/basics#adapting-based-on-props

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM