在没风的地方找太阳  在你冷的地方做暖阳 人事纷纷  你总太天真  往后的余生  我只要你 往后余生  风雪是你  平淡是你  清贫也是你 荣华是你  心底温柔是你  目光所致  也是你 想带你去看晴空万里  想大声告诉你我为你着迷 往事匆匆  你总会被感动  往后的余生  我只要你 往后余生  冬雪是你  春花是你  夏雨也是你 秋黄是你  四季冷暖是你  目光所致  也是你 往后余生  风雪是你  平淡是你  清贫也是你 荣华是你  心底温柔是你  目光所致  也是你
jQuery火箭图标返回顶部代码 - 站长素材

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

posted @ 2020-05-21 12:31  艺术诗人  阅读(7064)  评论(0编辑  收藏  举报