React 中 使用 ts

时间:2020-05-21
本文章向大家介绍React 中 使用 ts ,主要包括React 中 使用 ts 使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

react中使用ts,难点在于定义数据类型接口和对传入的数据进行校验。

icon.tsx

import React from 'react';
const Icon = ({ name, ...restProps}) => {
    return (
        <svg {...restProps}>
            <use xlinkHref={`#${name}`}/>
        </svg>
    );
};
export default Icon;

index.tsx

import * as React from 'react';
import ReactDom from 'react-dom';
import Icon from './icon/icon';

const fn =  (e) => {
  console.log((e))
};

ReactDom.render(
  <Icon name='wechat'/>, 
  document.getElementById('root')
);

然后对传入的name进行类型确定
icon.tsx

import React from 'react';

interface IconProps{
   name: string;
}

 const Icon: React.FunctionComponent<IconProps>  // React.FunctionComponent为对icon组件的类型测试,后面是传入的值的类型
=({ name, ...restProps})=> {
    return (
        <svg {...restProps}>
            <use xlinkHref={`#${name}`}/>
        </svg>
    );
};

export default Icon;

当然在传值的过程不只传个静态数据,还可能会传个事件,事件的类型判断和静态数据的不一样, 事件的类型判断如下:

interface IconProps extends React.SVGAttributes<SVGElement> {
    name: string;
    onClick: React.MouseEventHandler<SVGElement>
}

当然,传入的事件也需要进行一下类型判断:

const fn: React.MouseEventHandler<SVGAElement | SVGUseElement> = (e) => {
  console.log((e.target as HTMLDivElement))
};

原文出自:https://www.jianshu.com/p/9e08341d2967

原文地址:https://www.cnblogs.com/art-poet/p/12929949.html