多语言展示
当前在线:773今日阅读:19今日分享:20

在react中的ts使用教程

一个简单的ts+react例子就写好了。
方法/步骤
1

icon.tsximport React from 'react';const Icon = ({ name, ...restProps}) => {    return (                                );};export default Icon;

2

index.tsximport * as React from 'react';import ReactDom from 'react-dom';import Icon from './icon/icon';const fn =  (e) => {  console.log((e))};ReactDom.render(  ,  document.getElementById('root'));

3

然后对传入的name进行类型确定icon.tsximport React from 'react';interface IconProps{   name: string;} const Icon: React.FunctionComponent  // React.FunctionComponent为对icon组件的类型测试,后面是传入的值的类型 =({ name, ...restProps})=> {    return (                                );}; export default Icon;

4

当然在传值的过程不只传个静态数据,还可能会传个事件,事件的类型判断和静态数据的不一样, 事件的类型判断如下interface IconProps extends React.SVGAttributes {    name: string;    onClick: React.MouseEventHandler}

5

当然,传入的事件也需要进行一下类型判断const fn: React.MouseEventHandler = (e) => {  console.log((e.target as HTMLDivElement))};

推荐信息