【问题标题】:Passing prop to styled component将 prop 传递给样式化组件
【发布时间】:2019-07-25 12:46:57
【问题描述】:

我正在尝试找到一种方法来动态创建“居中此 div”组件。这段代码目前可以工作,但有点冗长,也不是很枯燥:

const Rel = styled.div`
    position: relative;
    height: 100%;
    width: 100%;
    `

const Abs = styled.div`
    position: absolute;
    top: 50%;
    `

const LeftAbs = styled(Abs)`
    left: 0;
    transform: translateY(-50%);
`
const RightAbs = styled(Abs)`
    right: 0;
    transform: translateY(-50%);
`
const CenterAbs = styled(Abs)`
    left: 50%;
    transform: translate(-50%, -50%);
`


const Centered = ({ children, ...props }) => {

    let abs = <CenterAbs>{children}</CenterAbs>

    if (props.center) {
        abs = <CenterAbs>{children}</CenterAbs>
    } else if (props.left) {
        abs = <LeftAbs>{children}</LeftAbs>
    } else {
        abs = <RightAbs>{children}</RightAbs>
    }

    return (
        <Rel>
          {abs}
        </Rel>
    )


}

我想以不同的方式通过将道具向下传递给 Abs 组件来做到这一点,就像这样(下图),其中顶级元素 Centered 接收道具,然后动态地将其传递到下面的组件中。

const Abs = styled.div`
    position: absolute;
    top: 50%;
    ${props => props.left ? "left: 0;" : "right: 0;"}
    `



const Centered = ({ children, ...props }) => {

    const { direction } = props

    return (
        <Rel>
          <Abs direction>{children}</Abs>
        </Rel>
    )

}

// ...passed into:
const Header = () => {
  return (
    <HeaderContainer>
      <Centered direction="left">
        <h1>Raph37</h1>
      </Centered>
    </HeaderContainer>
  )
}

这可能(或最佳实践)吗?我尝试了许多不同的方法,希望得到一些指导。

【问题讨论】:

    标签: css reactjs styled-components


    【解决方案1】:

    根据文档的section,您所写的内容应该几乎可以工作,并且您的方法是执行此操作的正确方法之一。

    使用&lt;Abs direction&gt;,您将传递direction = true。 这不是你想要的。用&lt;Abs direction={direction}&gt;修改它。

    请注意,有时您不希望修改 UI 组件,无论您身在何处,都可以使用来自 styled-component 的 css 属性覆盖它。例如,您可以这样做:

    import styled, { css } from 'styled-components'
    
    const Abs = styled.div`
        position: absolute;
        top: 50%;
    `
    
    const Centered = ({ children, direction }) =>
        <Rel>
          <Abs css={direction === 'left' ? css`left: 0;` : css`right: 0;`}>
            {children}
          </Abs>
        </Rel>
    }
    

    你可以在styled-componenthere找到更多关于css prop的信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-30
      • 2019-05-17
      • 2020-10-28
      • 1970-01-01
      • 2020-05-22
      • 2020-06-06
      • 1970-01-01
      • 2019-06-26
      相关资源
      最近更新 更多