如何用样式化的组件和打字稿覆盖Button Ant Design?

时间:2019-10-21 18:46:00

标签: reactjs typescript styled-components antd

我想用打字稿和样式化组件覆盖Button Ant Design,以个性化样式。但是当我尝试te效果不好。

我尝试了一些测试,但从来没有良好的显示效果。

我尝试这样How to wrap up Ant Design with Styled Components and TypeScript?,但没有结果。

但是结果不是ant Design组件的样式,而是Button继承了Button ant设计及其道具。

ButtonStyledComponent

import { Button as AntButton } from "antd";
import { NativeButtonProps } from "antd/lib/button/button";
import * as React from "react";
import styledComponents from "styled-components";

export const Button = styledComponents<NativeButtonProps>(props => (
  <AntButton {...props} />
))`
   pType: string;
   pSize: string;
   pShape: string;
`;

按钮

import * as React from "react";
import { Button } from "./ButtonStyleComponent";

export interface ButtonProps {
  pType?: "primary" | "secondary" | "danger";
  pSize?: "small" | "medium" | "large";
  pShape?: "round" | "rect";
}

class Button extends React.Component<ButtonProps> {
  render() {
    return (
      <Button
        {...this.props}
        pType={this.props.pType}
        pSize={this.props.pSize}
        pShape={this.props.pShape}
      >
        {this.props.children}
      </Button>
    );
  }
}

导出{按钮};

问题是当我执行此代码时,我看到的只是一个难看的灰色Button,而没有看到带有Ant Design Button设计的Button。

另一个问题是,当我尝试调用Ant Design Button的方法时,该方法无法识别(例如:onClick方法)。

2 个答案:

答案 0 :(得分:0)

以下是我使用antd

完成的操作的一个示例
import { Button } from 'antd'
import { ButtonProps } from 'antd/lib/button'
import useStyles from 'isomorphic-style-loader-forked/useStyles'
import React from 'react'
import s from './CardButton.css'

interface CardButtonProps extends ButtonProps {
  onClick?: () => void
}

const CardButton = ({ children, onClick, ...rest }: CardButtonProps) => {
  useStyles(s)
  return (
    <Button ghost type="primary" className={s.root} onClick={onClick} {...rest}>
      {children}
    </Button>
  )
}
export default CardButton

不过,对于您的问题,此答案可能会更How to wrap up Ant Design with Styled Components and TypeScript?

答案 1 :(得分:0)

在固定组件网站的常见问题解答中有答案。
在下面,我将覆盖Antd按钮的默认背景颜色。

import React from "react";
import "antd/dist/antd.css";
import { Button } from "antd";
import styled from "styled-components";

const MyButton = styled(Button)`
  &&& {
    background: red;
  }
`;

export default function App() {
  return (
    <div className="App">
      <MyButton>Click</MyButton>
    </div>
  );
}