[英]Conditionally rendering a component with styled components
With styled components, I can pass in values and then get conditional css based on those values.使用样式化的组件,我可以传入值,然后根据这些值获得有条件的 css。 For instance, I can do,例如,我可以这样做,
const ContainerStyled = styled.div<{isOpen: boolean}>`
${({ isOpen }) => isOpen
? background-color: red
: ''
}
`
However, I'm wondering if it's possible to conditionally render a different component, based on that value?但是,我想知道是否可以根据该值有条件地渲染不同的组件? For instance, something like,例如,类似的东西,
const ContainerStyled = styled(isOpen ? ArrowUpIcon : ArrowDownIcon)`
${({ isOpen }) => isOpen
? background-color: red
: ''
}
`
I'm guessing that you asking if you can change the styled target depending on condition .我猜你问是否可以根据条件更改样式目标。
For that you need to make simple steps:为此,您需要执行简单的步骤:
className
prop .自定义组件必须传递className
prop 。as
API with condition.在有条件的情况下as
API 。 In the next example, the button toggles between rendering a styled.div
and styled(Component)
.在下一个示例中,按钮在呈现styled.div
和styled(Component)
之间切换。
const Container = styled.div`
width: 100px;
height: 100px;
background-color: ${({ isOpen }) => (isOpen ? `red` : `blue`)};
`;
const Component = ({ className }) => <div className={className}>Hello</div>;
const App = () => {
const [isOpen, toggle] = useReducer(p => !p, false);
return (
<>
<Container as={isOpen ? Component : 'div'} isOpen={isOpen} />
<button onClick={toggle}>Toggle</button>
</>
);
};
You can attach as
polymorphic prop using attrs
chainable method based on passed isOpen
prop:您可以使用基于传递的isOpen
的attrs
可链接方法附加as
多态属性:
const ContainerStyled = styled(ArrowDownIcon).attrs(({ isOpen }) => ({
as: isOpen ? ArrowUpIcon : undefined
}))`
background-color: ${({ isOpen }) => isOpen ? 'red' : ''};
`;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.