zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    lucene中创建索引库
    商城后台上架商品列表查询的书写全过程
    Linux命令英文全称
    商品品牌分页、过滤、排序查询的完成流程
    axios使用步骤详解(附代码)
    使用CORS处理跨域请求
    npm 是干什么的?
    Mybatis通用Mapper介绍和使用
    FastDFS的理解和分析
    CDN服务的含义
  • 原文地址:https://www.cnblogs.com/art-poet/p/12929949.html
Copyright © 2011-2022 走看看