在react中的ts使用教程

 时间:2024-10-28 22:52:11

1、icon.tsximport React from 'react';const Icon = ({ name, ...restProps}) => { return ( <svg {...restProps}> <use xlinkHref={`#${name}`}/> </svg> );};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( <Icon name='wechat'/>, document.getElementById('root'));

3、然后对传入的name进行类型确定icon.tsximport 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;

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

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

  • 女性吃什么让身材更加苗条
  • 如何做大盘鸡面更好吃?
  • U9如何导入备份数据
  • 猪肉粉丝包的做法
  • 庆余年手游装备实力提升攻略详解
  • 热门搜索
    动物成语大全 四字成语 分析方法有哪些 绕口令大全 豌豆怎么做好吃 炒饼的家常做法 川菜家常菜 鸡肉怎么做好吃 风筝图片大全 中间的圆点怎么打 海参的家常做法大全