reactjs - 使用 styled-components 进行条件渲染
问题描述
我在 React 应用程序中使用 styled-components 库,我有这个块,例如:
const Wrapper = styled.div`
background: red;
`;
如果道具具有设定值,我需要添加一些其他样式,例如:
const Wrapper = styled.div`
background: red;
color: white; // color should be added only if this.props.myProps == 'ok'
`;
最好的方法是什么?
解决方案
对于一种风格:
const Wrapper = styled.div`
background: red;
color: ${props => props.myProps === 'ok' && 'white'};
`;
对于多种样式:
const Wrapper = styled.div`
background: red;
${props => {
if (props.myProps === 'ok') return `
background-color: black;
color: white;
`
}}
`;
另一种选择是使用styled.css
:
// Define a pure group of css properties
const okStyle = styled.css`
background-color: black;
color: white;
`;
// Reuse okStyle inside a styled component
const Wrapper = styled.div`
background: red;
${props => props.myProps === 'ok' && okStyle}
`;
推荐阅读
- git - 以前的 git revert 正在删除新合并中的文件
- java - 在springboot应用的application.properties中配置map
- java - 拆分字符串后出现 NumberFormatException
- vba - 如何在工作表之间复制在vba中,我试图录制宏但它不起作用
- javascript - 输入点击区域大于输入,导致按钮不起作用
- javascript - 使用 Formik 构建向导时不能在子组件中使用道具
- sonarqube - Sonarqube 的分支视图中未显示“更多”菜单
- php - 从数组中获取值有一个多行
- javascript - 构建完成后运行汇总插件
- python - python:从输入点获取周长点