如何用带样式的组件覆盖 React Component 样式?

How to override React Component styles with styled components?

我有一个 <DiscoverButton> React 组件,它有一些样式并且在单击时会执行 smth。顺便说一下,我正在使用样式化组件进行样式化。我需要创建一个几乎相同的 <ReturnButton> React 组件,唯一的区别是宽度。

这是我想做的,但没有达到我想要的效果:

DiscoverButton.tsx

export const BigButton = styled.button`
  width: 100%;
  height: 3.5rem;
  background-color: var(--lighter-black);
  border: none;
  border-radius: 0.4rem;
  color: var(--cultured-white);

  transition: background-color 0.7s, color 0.7s;

  &:hover {
    background-color: transparent;
    border: 2px solid var(--lighter-black);
    color: var(--lighter-black);
  }
`;

export const DiscoverButton: React.FC<Props> = ({ children, ...props }) => {
  return (
    <BigButton onClick={() => // do smth with props >
      {children}
    </BigButton>
  );
};

这就是我挣扎的地方: ReturnButton.tsx:

const ReturnButtonStyled = styled(DiscoverButton)`
  width: 7%;
`;

export const ReturnButton: React.FC<Props> = ({ children, ...props }) => {
  return (
    <ReturnButtonStyled id={props.id} btnTitle={props.btnTitle}>
      {children}
    </ReturnButtonStyled>
  );

您应该将 className 属性传递给呈现样式的组件。

export const DiscoverButton: React.FC<Props> = ({ children, className, ...props }) => {
  return (
    <BigButton
      className={className}
      onClick={() => // do smth with props
    >
      {children}
    </BigButton>
  );
};

更新

Caveat with className

When defining a component you will need to mark className as optional in your Props interface

interface Props {
  .... other prop types ....
  /* This prop is optional, since TypeScript won't know that it's passed by the wrapper */
  className?: string,
  .... other prop types ....
}

您也不一定需要以手动将无关属性传递给样式化组件的方式编写功能组件。

示例:

interface Props {
  btnTitle?: string,
  children: any,
  className?: string,
  id?: string,
  onClick: React.MouseEventHandler<HTMLButtonElement>,
}

const BigButton = styled.button`
  .... base styles ....
`;

const DiscoverButton: React.FC<Props> = ({ children, className, onClick }) => (
  <BigButton
    className={className}
    onClick={(...args) => {
      console.log("Did something with the props");
      onClick(...args);
    }}
  >
    {children}
  </BigButton>
);

const ReturnButton: React.FC<Props> = styled(DiscoverButton)`
  width: 7%;
`;