1、项目创建
npx create-react-app myapp --scripts-version=react-scripts-ts
tsconfig.json // 之前编译选项参考配置
2、React的引入
import * as React from 'react'
import * as ReactDOM from 'react-dom'
3、组件的创建
尽量使用函数组件
4、数据传递props
interface申明参数
interface IProps{
name: string, //必选属性
age?: number, //可选属性
}
export default class Component extends React.Component<IProps, any>{} //这样使用
5、状态管理state
// interface申明状态
interface IState{
count: number, //必选
title?: string, //可选
}
export default class Component extends React.Component<{}, ISTate>{ //这样使用
//实现State
方法一
constructor(props: any){
super(props)
this.state = {
count: 1
}
}
方法二
public readonly state: Readonly<IState> = {
count: 1
}
方法三
state = {
count: 1
}
}
class xxx extends React.Component<IProps, IState> //泛型接口定义Props和State状态
6、事件处理
子组件向父组件传参数 使用回调函数
问题:如果父组件是函数组件,接收到子组件传过来的消息怎么在组件中使用?
7、条件渲染和列表渲染
state = {
list: Array<any> //数组类型
}
render(){
return(
<div> //div里面进行条件渲染和列表渲染 return({})是错误的
{
list.length>0
?
<ul>
list.map(item => {
return <li key={item.id}>{item.title}</li>
})
</ul>
:
<div>数据为空...</div>
}
</div>
)
}
8、第三方UI Antd
https://ant.design/docs/react/use-in-typescript-cn
yarn add antd
import { Button } from 'antd';
<Button type="primary"></Button>
index.css全局引入@import '~antd/dist/antd.css'; // 推荐按需引入,全局引入性能消耗较大
9、路由
// https://github.com/molefrog/wouter
// yarn add wouter
import { Router, Switch, Route } from 'wouter';
const AppRouter = () => (
<div>
<Router>
<Switch>
<Route path="/" component={Home} />
<Route path="/list" component={List} />
<Route component={NotFoundPage} />
</Switch>
</Router>
</div>
);
10、Redux
// 还没开始