使用react搭建组件库(二):react+typescript

1 使用了react官方脚手架:create-react-app

https://github.com/facebook/create-react-app

npm run eject 可以打开配置文件

自定义配置文件

执行安装: npx create-react-app ts-with-react --typescript 

npx 只有在npm5.2以上版本才有

1、避免安装全局模块:临时命令,使用后删除,再次执行的时候再次下载

2、调用项目内部安装的模块用起来更方便:比如 在package.json文件中安装了一个依赖:mocha,如果想执行有两种方法:

 2.1 在scripts中定义   

{
   "script":{
       "test":"mocha --version"
    }  
}

2.2 在命令行中执行  node_modules/.bin/mocha --version 

而使用npx的话 则只需要执行:  npx mocha --version 

首先新建一个hello组件:components/hello.jsx

import React from 'react'
interface IHelloProps {
  message?: string;//因为设置了props的默认值,这里用?表示有无都可
}

/*
const Hello = (props:IHelloProps) => {
  return <h2>{props.message}</h2>
}
*/
const Hello: React.FC<IHelloProps> = (props) => {
  //FC是 react 官方提供的一个 interface 的简写:FunctionComponent,接收一个范型
  //这样Hello包含了很多静态方法
  return <h2>{props.message}</h2>
}
Hello.defaultProps = {
  message: "Hello World"
}

export default Hello

猜你喜欢

转载自www.cnblogs.com/xiaozhumaopao/p/12636559.html