将 prop 传递给样式化的组件

Passing prop to styled component

我正在尝试找到一种动态创建 'center this 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>
  )
}

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

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

<Abs direction>,你超过了 direction = true。 这不是你想要的。修改为 <Abs direction={direction}>.

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

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-component here.

中找到有关 css 道具的更多信息