首页 > 解决方案 > 如何一次将道具传递给所有样式化的组件css属性?

问题描述

而不是像这样反复挑选道具......

const BubbleContainer = styled.View`
  background-color: ${({ theme }) => (theme.debug ? 'white' : 'blue')};
  border-width: ${({ theme }) => (theme.debug ? '1px' : '0px')};
  color: ${({ theme }) => (theme.debug ? 'red' : 'black')};
`;

我想这样做一次(伪代码)......

const BubbleContainer = styled.View`
  ${({ theme }) =>
    background-color: {theme.debug ? 'white' : 'blue'};
    border-width: {theme.debug ? '1px' : '0px'};
    color: {theme.debug ? 'red' : 'black'};
  }
`;

标签: reactjsstyled-components

解决方案


你很亲密。您只需要使用反引号字符串进行插值和多行支持。

const BubbleContainer = styled.View`
  ${({ theme }) => `
    background-color: ${theme.debug ? 'white' : 'blue'};
    border-width: ${theme.debug ? '1px' : '0px'};
    color: ${theme.debug ? 'red' : 'black'};
  `}
`;

有很多选择,这可能更清晰一点:

const BubbleContainer = styled.View`
  background-color: blue;
  border-width: 0px;
  color: black;

  ${({ theme }) => theme.debug && `
    background-color: white;
    border-width: 1px;
    color: red;
  `}
`;

推荐阅读