使用命令创建项目
生成一个全新的 ts + react 的模版 可直接使用指令:npm create react-app my-app --template typescript
,该模板包含了全套正常运行React所需要的的包和配置
,无需再额外手动安装typescript(本章就使用这个命令)
创建项目
npm create react-app my-app --template typescript
如要使用其他第三方库,如路由需要安装路由 (两个都要装)
npm i react-router-dom
npm i @types/react-router-dom
状态管理器react-redux
npm i react-redux
npm i @types/react-redux
点我前往在typescript中使用antd教程
新建组件(后缀名一般都为tsx)
import * as React from 'react';
import ReactDOM from 'react-dom'
//定义接口
export interface Home{
home?:any
}
export interface Home2{
num:number,
str:string,
flag:boolean,
show?:any,
}
class Homes extends React.Component<Home,Home2>{
constructor(props:Home){
super(props)
this.state = { //这里与Home2里的同步
num:1,
str:"字符串",
flag:false,
show:"任意类型,可有可无"
}
}
//这里可以写方法了
componentDidMount(){
this.getList(10);
}
getList(num:any):void{
console.log(num)
}
render(){
return(<div>
<h1>这里开始可以写内容了</h1>
<div className="header"></div>
<div className="footer"></div>
</div>)
}
}
export default Homes