css - 将 prop 传递给样式化的组件

标签 css reactjs styled-components

我正在尝试找到一种动态创建“居中此 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>
    )


}

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

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 组件,您可以使用 css 覆盖它。 Prop 来自 styled-component无论你在哪。例如,您可以这样做:

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

您可以找到有关 css 的更多信息 Prop styled-component here .

关于css - 将 prop 传递给样式化的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54979296/

相关文章:

css - 将 Strong 标签中的内容更改为类

reactjs - 通量多个存储实例

reactjs - Typescript Reactjs Jest/ enzyme 错误 - 'Type ' 任何 []' is missing the following properties...'

javascript - 样式化组件 - 根据 props 有条件地渲染整个 css block

javascript - 如何将 Styled Component 样式应用于自定义 React 组件?

jquery - 如何从 iframe 隐藏滚动条?

html - 如何在不影响输入的宽度和高度的情况下,将svg图像作为背景图标添加到具有宽度和高度的输入右侧

javascript - 在 Javascript 中迭代元素数组时,并非每个元素的类都会更新

ajax - 使用 JEST 进行 ajax 调用的单元测试 React 组件

javascript - 如何在 next.js 应用中使用谷歌分析?