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