Как стилизовать все дочерние компоненты из родительского компонента через стилизованный компонент - PullRequest
0 голосов
/ 17 апреля 2020

Я боролся со стилизацией дочерних компонентов от родительского компонента с помощью styled-компонентов. Ниже приведен код. Я прокомментировал, где я изо всех сил и чего я хочу добиться. Документы с элементами стиля не помогают.

Ссылка Codesandbox: https://codesandbox.io/s/adoring-pare-exjjt?file= / src / App. js

    import React from 'react';
    import { render } from "react-dom";
    import styled from 'styled-components'
    import { Button, Grid ,Container} from 'semantic-ui-react'
    import PropTypes from 'prop-types'

    const mID = 'test'

    const StyledBlock = styled(Container)`
    {/*i don't want to style here */}

      /* height: 450px;
      background-color: #f7f7f7;
      @media only screen and (max-width: 767px) and (min-width: 320px) {
        height: 550px;
      } */
    `
    const StyledSection = styled.section`
      background: #ffffff;
      box-shadow: 0px 1px 0px #dfdfdf;
      margin: 12% 10% 10% 30%;
      height: 150px;
      width: 170px;
      @media only screen and (max-width: 767px) and (min-width: 320px) {
        margin: 10% 0 25% 25%;
        width: 172px;
      }
    `
    const Header = styled.h4`
      text-align: center;
      position: relative;
      top: 10%;
    `
    const StyledButton = styled(Button)`
      position: relative;
      bottom: -60px;
      margin: 0px;
      width: 100%;
      top: 9.32%;
    `

    const Report = (name) => {
      const handleClick = async (e) => {
        console.log(e)
      }

      return (
        <Grid.Column key={name} className={`${mID}_preview`}>
          <StyledSection>
            <Header>{name}</Header>
            <StyledButton secondary onClick={() => handleClick(name)} >
              Download
            </StyledButton>
          </StyledSection>
        </Grid.Column>
      )
    }

    const Reports = () => {
    return(
      <Container>
        <StyledBlock>
          <Grid>
            <Grid.Row>{["deen","john"].map((name) => Report(name))}</Grid.Row>
          </Grid>
        </StyledBlock>
      </Container>
    )}

    Reports.propTypes = {
      names: PropTypes.array,
      onlineShowId: PropTypes.number
    }

//below code is not able to pass css. don't see these css anywhere applied . why ?
    const StyledReports = styled(Reports)`
    background-color: yellow
     .${mID} {
        &_preview {
          color: red
        }
     }

     ${StyledBlock}{
      background-color: red
     }
    `

    render(<StyledReports />, document.getElementById("root"))

1 Ответ

0 голосов
/ 17 апреля 2020

Я нашел решение

Вам нужно иметь className на родительском компоненте, как этот

import React from 'react';
import { render } from "react-dom";
import styled from 'styled-components'
import { Button, Grid ,Container} from 'semantic-ui-react'
import PropTypes from 'prop-types'

const mID = 'test'

const StyledBlock = styled(Container)`
{/*i don't want to style here */}
  background-color: yellow ;
  height: 450px;
  @media only screen and (max-width: 767px) and (min-width: 320px) {
    height: 550px;
  }
  > * { //applies for all under parent class ,class that is applied by SC on parent
    color: magenta
  }
  & .${mID}__column{ //all elements under & i.e parent class (which is StyledBlock) with class {mID}__column
    color :green;
  }
`
const StyledSection = styled.section`
  background: #ffffff;
  box-shadow: 0px 1px 0px #dfdfdf;
  margin: 12% 10% 10% 30%;
  height: 150px;
  width: 170px;
  @media only screen and (max-width: 767px) and (min-width: 320px) {
    margin: 10% 0 25% 25%;
    width: 172px;
  }
`
const Header = styled.h4`
  text-align: center;
  position: relative;
  top: 10%;
`
const StyledButton = styled(Button)`
  position: relative;
  bottom: -60px;
  margin: 0px;
  width: 100%;
  top: 9.32%;
`

const Report = (name) => {
  const handleClick = async (e) => {
    console.log(e)
  }

  return (
    <Grid.Column key={name} className={`${mID}__column`}>
      <StyledSection>
        <Header>{name}</Header>
        <StyledButton secondary onClick={() => handleClick(name)} >
          Download
        </StyledButton>
      </StyledSection>
    </Grid.Column>
  )
}

const Reports = ({className}) => {
  console.log('className ',className)
return(
  <Container className={className}>
    <StyledBlock>
      <Grid>
        <Grid.Row>{["deen","john"].map((name) => Report(name))}</Grid.Row>
      </Grid>
    </StyledBlock>
  </Container>
)}

Reports.propTypes = {
  names: PropTypes.array,
  onlineShowId: PropTypes.number
}

const StyledReports = styled(Reports)`
   background-color:blue; //to apply this,SC need a className on this element to apply
 .${mID} {
    &__column {
      color: gold
    }
 }

 ${StyledBlock}{
  background-color: red  ; //higher specificity than in styledblock
 }
`

render(<StyledReports />, document.getElementById("root"))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...