React UI 造轮子笔记

1. 项目搭建小知识点

(1) 设置 src 为baseUrl

为了方便引用文件,在 tsconfig.json 文件的 compilerOptions 配置项里添加配置: "baseUrl": "src"
此时引用路径可以直接写 dir/comp.tsx ,这个路径相当于 src/dir/comp.tsx

2. utils 方法

(1)设置多个classNames

props 接收的 className,如果直接设置,当 props.className 不存在时,会变成 undefined

<div className={`container ${props.className}`}>{props.children}</div>
// 若props.className 不存在,在 html 中,会变成 <div class="container undefined">{props.children}</div>

为了解决这个问题,封装一个函数:

const classNames = (...names: (string|undefined)[]):string=>{
  // filter(Boolean) 相当于:filter(item=>item)
  return names.filter(Boolean).join(' ');
}
export default classNames;

(2)给className加前缀

为了避免类名冲突,给自己的库的类名加上项目名称的前缀,但是每次都要自己加很冗余,写一个高阶函数来解决这个问题:

const scopedClassMaker = (prefix: string) => {
  return function (className: string) {
    return [prefix, className].filter(Boolean).join('-');
  };
};
export default scopedClassMaker;

使用时:

 // 给所有的类名加react-ui-的前缀
const sc = scopedClassMaker('react-ui');

<div className={sc('mask')}></div>

3. 展示代码

用到两个库:yarn add -D raw-loader prism-react-renderer

  • raw-loader:获取代码
require(`!!raw-loader!./icon.example`).default
  • prism-react-renderer:代码高亮
import Highlight, { defaultProps } from 'prism-react-renderer';

 <Highlight {...defaultProps} code={props.code.trim()} language="tsx">
      {({ className, style, tokens, getLineProps, getTokenProps }) => (
        <pre className={className} style={style}>
          {tokens.map((line, i) => (
            <div {...getLineProps({ line, key: i })}>
              {line.map((token, key) => (
                <span {...getTokenProps({ token, key })} />
              ))}
            </div>
          ))}
        </pre>
      )}
    </Highlight>

4. 项目部署:

使用库来部署项目:gh-pages
教程:https://github.com/gitname/react-gh-pages

步骤:

  • 安装:npm install gh-pages --save-dev
  • 在项目的 package.json 文件里的最上面一行添加 homepage: "homepage": "https://gitname.github.io/projectname"
  • 添加脚本命令:
"scripts": {
  //...
  "predeploy": "npm run build",
  "deploy": "gh-pages -d build"
}
  • 运行脚本:npm run deploy
  • 将本地代码上传到 github
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值