首页 > 其他 > 详细

React 中 使用 ts

时间:2020-05-21 13:21:34      阅读:64      评论:0      收藏:0      [点我收藏+]

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

React 中 使用 ts

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!