导读
开发环境
版本号 | 描述 | |
---|---|---|
node -v | v14.20.0 | |
npm -v | 6.14.6 | |
tsc -v | 4.7.4 | |
ts-node -v | 10.9.1 |
使用CRA创建支持TS的项目
项目创建
参考文章:【TypeScript】使用CRA创建支持TS的React项目(从踩坑到放弃) https://blog.csdn.net/kinghzking/article/details/126188004
核心命令:npx create-react-app react-ts-basic --template typescript
。
React支持TS的项目目录结构说明
相比非TS项目的三个变化
react-app-env.d.ts
tsconfig.json
https://www.typescriptlang.org/tsconfig
React函数组件
React常用类型及属性
示例代码如下所示:
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
// import App from './App';
import reportWebVitals from './reportWebVitals';
type Props = {
name: string, age?: number}
const Hello: React.FC<Props> = ({
name, age}) => {
return <div>
您好,我叫:{
name},我{
age}岁了。
</div>;
}
const App = () => {
return <div>
<Hello name='khz' age={
12} />
</div>
}
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(<App />);
React函数组件属性的默认值
事件和事件对象
示例代码:
React类组件
组件类型
属性和属性默认值
状态和事件
参考资料
- 《黑马程序员前端TypeScript教程》https://www.bilibili.com/video/BV14Z4y1u7pi
- TypeScript 教程 https://www.runoob.com/typescript/ts-tutorial.html
- DefinitelyTyped https://github.com/DefinitelyTyped/DefinitelyTyped
- TS官方查询
@types/*
库的地址:https://www.typescriptlang.org/dt/search?search=