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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM