在反应中重用 const 对象

Reuse const object in react

假设我想在对象中使用相同的代码块,并添加:

const styles = {
  styleA: `
    background-color: red;
    color: silver;
  `,
  styleB: `
    background-color: green;
    color: white;
  `,
  styleC: `
    background-color: red;
    color: silver;
    font-size: 16px;
  `
};

如您所见,styleA 和 styleC 相似,除了 styleC 的字体大小不同。我怎样才能用 react (es6) 重写它,以便

styleA = styleC + 'font-size: 16px'; ?

或者是否有更好的方法来完全做到这一点?

你可以有这样的东西。

const createStyle = (bgColor, color, fontSize) => {

  return (
    `
    background-color: ${bgColor};
    color: ${color};
    ${fontSize ? `font-size: ${fontSize}` : null}; //if there is fontSize, return it
    `
  );
}

因此:

const styles = {
  styleA: createStyle('red', 'silver'),
  styleB: createStyle('red', 'silver', '16px')
};

您可以使用 styled-components 中的 css helper 来帮助从其他现成组件创建样式和混合。

例如,在您的情况下:

const styleA = css`
  background-color: red;
  color: silver;
`;

const styleB = css`
  background-color: yellow;
`;

const styles = {
  styleC: css`
    ${styleA}
    ${styleB}
    font-size: 32px;
  `
};

const MainHeading = styled.h2`
  ${styles.styleC}
`;