我正在尝试找到一种方法来动态创建“居中此 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 https://www.styled-components.com/docs/basics#adapting-based-on-props的文档。
With <Abs direction>
,你正在通过direction = true
。
这不是你想要的。修改它与<Abs direction={direction}>
.
请注意,有时您不希望修改 UI 组件,您可以使用css
支撑来自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
支撑styled-component
here https://medium.com/styled-components/announcing-native-support-for-the-css-prop-in-styled-components-245ca5252feb.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)