将 prop 传递给样式化组件 [英] Passing prop to styled component

查看:37
本文介绍了将 prop 传递给样式化组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找到一种方法来动态创建将此 div 居中"组件.这段代码目前有效,但有点冗长而且不是很枯燥:

I'm trying to find a way to dynamically create a 'center this div' component. This code currently works but is a bit verbose and not very dry:

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


}

我想以不同的方式通过将一个 prop 传递给 Abs 组件来完成它,就像这样(如下),其中顶级元素 Centered 接收一个 prop,然后动态地将它传递到下面的组件中.

I'd like to do it in a different way by passing a prop down to the Abs component, something like this (below) where the top level element Centered receives a prop, then dynamically passes that into the component beneath.

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

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

Is this possible (or best practice)? I've tried many different ways of doing it and would love a bit of a guidance.

推荐答案

根据此 部分 文档.

使用 ,您传递了 direction = true.这不是你想要的.用 修改它.

With <Abs direction>, you're passing direction = true. This is not what you want. Modify it with <Abs direction={direction}>.

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

Note that sometimes you won't wish to modify the UI component, and you can override it with the css prop from styled-component wherever you are. You can, for example, do this :

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 此处.

You can find more informations about css prop in styled-component here.

这篇关于将 prop 传递给样式化组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆