说说如何在React项目中使用Typescirpt
# 是什么
现在都是基于框架(vue,react)开发, 所以 ts 在框架中是如何实际应用的呢
- 依赖
npm i @types/react -s
npm i @types/react-dom -s
# 怎么用
import * as React from "react";
export const Logo = (props) => {
const { logo, className, alt } = props;
return <img src={logo} className={className} alt={alt} />;
};
# 无状态组件
interface IProps {
logo: string;
className: string;
alt: string;
}
import * as React from "react";
export const Logo = (props: IProps) => {
const { logo, className, alt } = props;
return <img src={logo} className={className} alt={alt} />;
};
# 有状态组件
import * as React from 'react'
interface IProps {
color: string,
size?: string,
}
interface IState {
count: number,
}
class App extends React.Component<IProps, IState> {
public state = {
count: 1,
}
public render () {
return (
<div>Hello world</div>
)
}
}
# hooks 组件
import React, { useEffect, useState } from 'react';
interface IProps {
logo: string;
className: string;
alt: string;
}
export const Logo = (props:IProps) => {
const { logo, className, alt } = props;
const [loading, setLoading] = useState(true)
useEffect(()=>{
if(logo){
setLoading(false)
}
}, [logo])
if(loading) return 'loading...'
return <img src={logo} className={className} alt={alt} />;
};
# 事件
常用Event 事件对象类型:
private updateValue(e: React.ChangeEvent<HTMLInputElement>) {
this.setState({ itemText: e.target.value })
}
ClipboardEvent<T = Element> 剪贴板事件对象
DragEvent<T = Element> 拖拽事件对象
ChangeEvent<T = Element> Change 事件对象
KeyboardEvent<T = Element> 键盘事件对象
MouseEvent<T = Element> 鼠标事件对象
TouchEvent<T = Element> 触摸事件对象
WheelEvent<T = Element> 滚轮事件对象
AnimationEvent<T = Element> 动画事件对象
TransitionEvent<T = Element> 过渡事件对象
上次更新: 2021/12/19, 18:05:42