從零開始構建自己的react組件庫

前面已經講過一些使用react創建組件庫的方式,這次玩真的,從0開始。

創建組件項目 

create-react-app react-ts-ui-demo --typescript

樣式系統文件的結構設計

安裝node-sass 

npm i node-sass -S

定義全局樣式 src/styles/_variables.scss

$white: #fff !default;
$gray-100:#f8f9fa !default;
$gray-200:#e9ecef !default;
$gray-300:#dee2e6 !default;
$gray-400:#ced4da !default;
$gray-500:#adb4db !default;
$gray-600:#6c757d !default;
$gray-700:#495057 !default;
$gray-800:#343a40 !default;
$gray-900:#212529 !default;
$black: #000 !default;

$blue:#0d6efd !default;
$indigo:#6610f2 !default;
$purple:#6f42c1 !default;
$pink:#d63384 !default;
$red:#dc3545 !default;
$orange:#fd7314 !default;
$yellow:#fadb14 !default;
$green:#52c41a !default;
$teal:#20c997 !default;
$cyan: #17a2b8 !default;

$primary: $blue !default;
$secondary:$gray-600 !default;
$success:$green !default;
$info: $cyan !default;
$warning: $yellow !default;
$danger: $red !default;
$light:$gray-100 !default;
$dark: $gray-800 !default;

$theme-colors:(
  "primary":$primary,
  "secondary":$secondary,
  "success":$success,
  "info":$info,
  "warning":$warning,
  "danger":$danger,
  "light":$light,
  "dark":$dark
);

$font-family-sans-serif:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji" !default;
$font-family-monospace: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace !default;
$font-family-base: $font-family-sans-serif !default;

// 字體大小
$font-size-base: 1rem !default;
$font-size-lg:$font-size-base*1.25 !default;
$font-size-sm:$font-size-base*0.875 !default;

// 後續定義省略

整合normalize.css到 src/styles/_reboot.scss中

拷貝 https://github.com/necolas/normalize.css 中的 normalize.css到_reboot.scss中 整合之前定義的變量

src/styles/_reboot.scss

// stylelint-disable at-rule-no-vendor-prefix, declaration-no-important, selector-no-qualifying-type, property-no-vendor-prefix

// Reboot
//
// Normalization of HTML elements, manually forked from Normalize.css to remove
// styles targeting irrelevant browsers while applying new styles.
//
// Normalize is licensed MIT. https://github.com/necolas/normalize.css


// Document
//
// Change from `box-sizing: content-box` so that `width` is not affected by `padding` or `border`.
*,
*::before,
*::after {
  box-sizing: border-box;
}

// Body
//
// 1. Remove the margin in all browsers.
// 2. As a best practice, apply a default `background-color`.
// 3. Prevent adjustments of font size after orientation changes in IE on Windows Phone and in iOS.
// 4. Change the default tap highlight to be completely transparent in iOS.
body {
  margin: 0; // 1
  font-family: $font-family-base;
  font-size: $font-size-base;
  font-weight: $font-weight-base;
  line-height: $line-height-base;
  color: $body-color;
  text-align: $body-text-align;
  background-color: $body-bg; // 2
  -webkit-text-size-adjust: 100%; // 3
  -webkit-tap-highlight-color: rgba($black, 0); // 4
}

// Future-proof rule: in browsers that support :focus-visible, suppress the focus outline
// on elements that programmatically receive focus but wouldn't normally show a visible
// focus outline. In general, this would mean that the outline is only applied if the
// interaction that led to the element receiving programmatic focus was a keyboard interaction,
// or the browser has somehow determined that the user is primarily a keyboard user and/or
// wants focus outlines to always be presented.
//
// See https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-visible
// and https://developer.paciellogroup.com/blog/2018/03/focus-visible-and-backwards-compatibility/

[tabindex="-1"]:focus:not(:focus-visible) {
  outline: 0 !important;
}


// Content grouping
//
// 1. Reset Firefox's gray color
// 2. Set correct height and prevent the `size` attribute to make the `hr` look like an input field
//    See https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_hr_size

hr {
  margin: $hr-margin-y 0;
  color: $hr-color; // 1
  background-color: currentColor;
  border: 0;
  opacity: $hr-opacity;
}

hr:not([size]) {
  height: $hr-height; // 2
}


// Typography
//
// 1. Remove top margins from headings
//    By default, `<h1>`-`<h6>` all receive top and bottom margins. We nuke the top
//    margin for easier control within type scales as it avoids margin collapsing.

%heading {
  margin-top: 0; // 1
  margin-bottom: $headings-margin-bottom;
  font-family: $headings-font-family;
  font-style: $headings-font-style;
  font-weight: $headings-font-weight;
  line-height: $headings-line-height;
  color: $headings-color;
}

// 後續定義省略

創建樣式入口文件 src/styles/index.scss

//config
@import "variables";

//layout
@import "reboot";

在src/index.tsx中引入 樣式入口文件

import './styles/index.scss'

 

組件編寫

安裝一個css的小工具 classnames

npm i classnames -S
npm i @types/classnames -S

從最簡單組件做起,創建一個button組件

src/compontents/Button/button.tsx

import React from 'react';
import classNames from 'classnames';
export enum ButtonSize{
  Large='lg',
  Small ='sm'
}

export enum ButtonType{
  Primary='primary',
  Default='default',
  Danger='danger',
  Link='link'
}

interface BaseButtonProps{
  className ?:string;
  disabled?:boolean;
  size?:ButtonSize;
  btnType?:ButtonType;
  children:React.ReactNode;
  href?:string;
}

type NativeButtonProps=BaseButtonProps & React.ButtonHTMLAttributes<HTMLElement>
type AnchorButtonProps=BaseButtonProps & React.AnchorHTMLAttributes<HTMLElement>

export type ButtonProps =Partial< NativeButtonProps & AnchorButtonProps>;

const Button: React.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===ButtonType.Link) && disabled
});
 

if(btnType===ButtonType.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:ButtonType.Default
}

export default Button;

爲button組件添加特有的樣式

src/components/Button/_style.scss

.btn{
  position:relative;
  display:inline-block;
  font-weight: $btn-font-weight;
  line-height:$btn-line-height;
  color:$body-color;
  white-space: nowrap;
  text-align:center;
  vertical-align: middle;
  background-image:none;
  border:$btn-border-width solid transparent;
  @include button-size($btn-padding-y,$btn-padding-x,$btn-font-size,$border-radius);
  box-shadow:$btn-box-shadow;
  cursor: pointer;
  transition: $btn-transition;
  &.disabled,&[disabled]{
     cursor:not-allowed;
     opacity:$btn-disabled-opacity;
     box-shadow: none;
     > * {
       pointer-events: none;
     }
  }
}

.btn-lg{
  @include button-size($btn-padding-y-lg,$btn-padding-x-lg,$btn-font-size-lg,$btn-border-radius-lg);
}

.btn-sm{
  @include button-size($btn-padding-y-sm,$btn-padding-x-sm,$btn-font-size-sm,$btn-border-radius-sm);
}

.btn-primary{
  @include button-style($primary,$primary,$white)
}

.btn-danger{
  @include button-style($danger,$danger,$white)
}

.btn-default{
  @include button-style($white,$gray-400,$body-color,$white,$primary,$primary)
}

.btn-link{
  font-weight: $font-weight-normal;
  color:$btn-link-color;
  text-decoration:$link-decoration;
  box-shadow: none;
  &:hover{
    color:$btn-link-hover-color;
    text-decoration:$link-hover-decoration;
  }
  &:focus,&.focus{
    text-decoration: $link-hover-decoration;
    box-shadow: none;
  }
  &:disabled,&.disabled{
    color:$btn-link-disabled-color;
    pointer-events:none;
  }
}

在src/styles下創建mixin文件 _mixin.scss
 

@mixin button-size($padding-y,$padding-x,$font-size,$border-raduis){
  padding:$padding-y $padding-x;
  font-size:$font-size;
  border-radius:$border-radius;
}

@mixin button-style(
  $background,
  $border,
  $color,
  $hover-background:lighten($background,7.5%),
  $hover-border:leight($border,10%),
  $hover-color:$color

){
  color:$color;
  background:$background;
  border-color:$border;
  &:hover{
    color:$hover-color;
    background:$hover-background;
    border-color:$hover-border;
  }
  &:focus,&.focus{
    color:$hover-color;
    background:$hover-background;
    border-color:$hover-border;
  }
  &:disabled,&.disabled{
    color:$color;
    background:$background;
    border-color:$border;
  }

}

將mixin文件和button的樣式文件導入到樣式入口文件 src/styles/index.scss中

//config
@import "variables";

//layout
@import "reboot";

// mixin
@import "mixin";

// button
@import "../components//Button/style"

在app.tsx中測試使用button組件 查看效果

具體源碼查看 https://github.com/lilugirl/react-ts-ui-demo

 

接下來將爲組件添加測試

熟悉jest

在根目錄下創建jest.test.js文件

test('test common matcher',()=>{
  expect(2+2).toBe(4)
  expect(2+2).not.toBe(5)
})

test('test to be true or false',()=>{
  expect(1).toBeTruthy()
  expect(0).toBeFalsy()
})

test('test nuimber',()=>{
  expect(4).toBeGreaterThan(3)
  expect(2).toBeLessThan(3)
})

test('test object',()=>{
  expect({name:'liuyi'}).toEqual({name:'liuyi'})
})

執行命令

npx jest jest-test.js --watch

爲button編寫測試文件

創建button測試文件  src/components/Button/button.test.tsx

import React from 'react'
import {render,fireEvent} from '@testing-library/react'
import Button,{ButtonProps,ButtonSize,ButtonType} from './button'



const defaultProps={
  onClick:jest.fn()
}

const testProps: ButtonProps={
  btnType:ButtonType.Primary,
  size:ButtonSize.Large,
  className:'klass'
}

const disabledProps:ButtonProps={
  disabled:true,
  onClick:jest.fn()
}


describe('test button component',()=>{
  it('should render the correct default button',()=>{

    const wrapper=render(<Button {...defaultProps}>Nice</Button>)
    const element= wrapper.getByText('Nice') as HTMLButtonElement
    expect(element).toBeInTheDocument()
    expect(element.tagName).toEqual('BUTTON')
    expect(element).toHaveClass('btn btn-default')
    expect(element.disabled).toBeFalsy();
    fireEvent.click(element)
    expect(defaultProps.onClick).toHaveBeenCalled()


  })
  it('should render the correct component based on different props',()=>{

    const wrapper=render(<Button {...testProps}>Nice</Button>)
    const element=wrapper.getByText('Nice')
    expect(element).toBeInTheDocument()
    expect(element).toHaveClass('btn-primary btn-lg klass')
  })

  it('should render a link when btnType equals link and href is provided',()=>{
    const wrapper=render(<Button btnType={ButtonType.Link} href="http://126.com">Link</Button>)
    const element=wrapper.getByText('Link')
    expect(element).toBeInTheDocument();
    expect(element.tagName).toEqual('A');
    expect(element).toHaveClass('btn btn-link')
   
 
})

it('should render disabled button when disabled set to true',()=>{
   const wrapper=render(<Button {...disabledProps}>Nice</Button>)
   const element=wrapper.getByText('Nice') as HTMLButtonElement
   expect(element).toBeInTheDocument();
   expect(element.disabled).toBeTruthy();
   fireEvent.click(element);
   expect(disabledProps.onClick).not.toHaveBeenCalled();
})
})

運行命令 npm run test

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章