import React, { FC, ButtonHTMLAttributes, AnchorHTMLAttributes } from 'react'
import classNames from 'classnames'
export type ButtonSize = 'lg' | 'sm'
export type ButtonType = 'primary' | 'default' | 'danger' | 'link'
interface BaseButtonProps {
className?: string;
/**设置 Button 的禁用 */
disabled?: boolean;
/**设置 Button 的尺寸 */
size?: ButtonSize;
/**设置 Button 的类型 */
btnType?: ButtonType;
children: React.ReactNode;
href?: string;
}
//https://www.typescriptlang.org/docs/handbook/utility-types.html
//联合类型&
type NativeButtonProps = BaseButtonProps & ButtonHTMLAttributes<HTMLElement>
type AnchorButtonProps = BaseButtonProps & AnchorHTMLAttributes<HTMLElement>
//TS文档里的Partial:将属性设置为可选 可能是A链接属性也可能是Button的属性
export type ButtonProps = Partial<NativeButtonProps & AnchorButtonProps>
/**
* 页面中最常用的的按钮元素,适合于完成特定的交互
* ### 引用方法
*
* ~~~js
* import { Button } from 'vikingship'
* ~~~
*/
export const Button: FC<ButtonProps> = (props) => {
const {
btnType,
className,
disabled,
size,
children,
href,
...restProps
} = props
// btn, btn-lg, btn-primary
const classes = classNames('btn', className, {
[`btn-${btnType}`]: btnType,
[`btn-${size}`]: size,
'disabled': (btnType === 'link') && disabled
})
if (btnType === 'link' && href ) {
return (
<a
className={classes}
href={href}
{...restProps}
>
{children}
</a>
)
} else {
return (
<button
className={classes}
disabled={disabled}
{...restProps}
>
{children}
</button>
)
}
}
Button.defaultProps = {
disabled: false,
btnType: 'default'
}
export default Button;
使用
import React from 'react'
import { action } from '@storybook/addon-actions'
import Button from './button'
const defaultButton = () => (
<Button onClick={action('clicked')}> default button </Button>
)
const buttonWithSize = () => (
<>
<Button size="lg"> large button </Button>
<Button size="sm"> small button </Button>
</>
)
const buttonWithType = () => (
<>
<Button btnType="primary"> primary button </Button>
<Button btnType="danger"> danger button </Button>
<Button btnType="link" href="https://google.com"> link button </Button>
</>
)