前提准备:
环境配置
安装node.js
官网安装:当前使用版本18.15.0
安装新的react应用:
运行命令新建react-app
npx create-react-app study-ts-app
当前版本:
- “react”: “^18.2.0”,
- “react-dom”: “^18.2.0”,
如果出现如下问题,无法安装依赖
可以尝试运行npm i react,如果报错,执行推荐命令
运行命令:
sudo chown -R 502:20 "/Users/rcdl/.npm"
命令详解参考:https://blog.csdn.net/wangcheeng/article/details/128165359
然后继续执行create-react-app
安装typeScript
npm i typescript --save
- “typescript”: “^5.0.4”,
在react中使用ts
参考:https://juejin.cn/post/7021674818621669389
在类组件
参数没有都可以被省略
// 使用方式:React.Component<P, S={}>{...}
// 示例:
import * as React from 'react'
interface IProps {
name: string;
}
interface IState {
age: number;
}
class Hello extends React.Component<IProps, IState> {
state = {
age: 18
};
render() {
return (
<div>
{
this.state.age}
{
this.props.name}
</div>
);
}
}
export default Hello;
React.Component
中P是props
类型的定义,S是state
类型的定义,都是泛型接口
React.PureComponent<P, S={
} SS={
}>{
...}
React.PureComponent
前两个值含义相同,第三个值代表getSnapshotBeforeUpdate
的返回值
在函数组件
在函数组件中,也可以接收一个参数(可省),参数表示props
的类型,示例如下
interface IProps {
name: string
}
const HelloFunction = (props: IProps) => {
const {name} = props;
return (
<div className="App">
<h1>hello world</h1>
<h2>{name}</h2>
</div>
);
}
export default HelloFunction;
定义函数组件的第二种方式,React.FunctionComponent<P={}>
来定义,也可以使用其简写React.FC<P={}>
,参数可省,示例如下
interface IProps {
name: string
}
const App: React.FC<IProps> = (props) => {
const {
name} = props;
return (
<div className="App">
<h1>hello world</h1>
<h2>{
name}</h2>
<