reactjs 如何继承另一个样式化组件的样式,同时将常规组件转换为样式化组件?

bgibtngc  于 2023-02-04  发布在  React
关注(0)|答案(1)|浏览(181)

我正在使用StyledComponents stying框架,这是我的常规react组件

const SelectButton = ({className,children, ...rest}) => {
  return (
     <select className = {className}{...rest}>
             {children}
          </select>
  );
}

我想通过调用styled()函数将此组件转换为样式化组件,为此,我将className属性附加到react组件(SelectButton)的DOM元素。

export const StyledSelectButton = styled(SelectButton);

但是我不想把css放在这个样式化的组件中,我想从不同样式化的组件StyledButton.js继承,它有以下css属性。

export const StyledButton = styled(Button).attrs(({ type }) => ({
  type: type || "button",
}))
  display: inline-block;
  height: auto;
  padding: 0.8rem 2rem;
  border: none;
  border-radius: 6px;
  font-weight: 500;
  font-size: 1.6rem;
  text-decoration: none;
  text-transform: capitalize;
  cursor: pointer;
  overflow: hidden;
  background-color: ${({ primary }) => (primary ? "#646ff0" : "#cccdde")};
  color: ${({ primary }) => (primary ? "white" : "#646681")};
  .__select {
    color: #585858;
    font-family: Poppins;
    padding: 1rem;
    border: none;
    background-color: #cccdde;
    width: 150px;
    cursor: pointer;
  };

我怎样才能做到呢?
我试过这样做,但我在重复我的代码。

export const StyledSelectButton = styled(SelectButton)
  display: inline-block;
  height: auto;
  padding: 0.8rem 2rem;
  border: none;
  border-radius: 6px;
  font-weight: 500;
  font-size: 1.6rem;
  text-decoration: none;
  text-transform: capitalize;
  cursor: pointer;
  overflow: hidden;
  background-color: ${({ primary }) => (primary ? "#646ff0" : "#cccdde")};
  color: ${({ primary }) => (primary ? "white" : "#646681")};
  &__select {
    color: #585858;
    font-family: Poppins;
    padding: 1rem;
    border: none;
    background-color: #cccdde;
    width: 150px;
    cursor: pointer;
  }
flseospp

flseospp1#

你可以做这样的事,

import styled, {css} from "styled-components";
import { StyledButton } from './Button';

  const style = css`
  color: #585858;
  font-family: Poppins;
  padding: 1rem;
  border: none;
  background-color: #cccdde;
  width: 150px;
  cursor: pointer;
`;

使用函数声明方法:

export function StyledSelectButton({ className, children, ...rest }){
   return (
     <select className={className} {...rest}>
       {children}
     </select>
   );
 };

要将此组件转换为样式化组件,请将其传递给styled()函数。

StyledSelectButton = styled(StyledButton).attrs((props) => ({
    as: "select"
}))`
  ${style}
`;

相关问题