React类型检查

301 阅读1分钟

函数组件

  • 使用FC类型进行函数组件声明
    • FCFunctionComponent的简写

interface IProps {
  name: string;
}

export const Demo: React.FC<IProps> = ({ name = 'wuw' }) => {
  return <h2>Hi {name}</h2>
}

  • 使用函数声明

interface IProps {
  id: string;
}

export function Demo(props: IProps) {
  return <h2>Hi ~</h2>
}

  • 泛型函数组件
interface ListProps<T> {
  list: T[],
  renderItem: (v: T, ind: number) => React.ReactNode
}

const Test = () => ({
  <List 
    list={['wuw', 'plom']}
    renderItem={(v, i) => {
      //
    }}
  />
})

  • 子组件声明

使用Parent.Child形式表示父子节点关系, 例如antdSelect.Option


interface CardProps {}
interface CardItemProps {}

export function Card(props: React.PropsWithChildren<CardProps>) {
  return <></>
}

Card.Item = (props: React.PropsWithChildren<CardItemProps>) => ({
  
})

类组件

  • ComponentPrueComponentre
import React, { Component } from 'react'
import { connect } from 'dva';

import { UmiComponentProps } from '@/common/type'

import Details from './components/details'

interface PageProps {
  details: any;
}

interface State {

}

type Props = PageProps & UmiComponentProps;

@connect(({ owner }) => ({
  details: owner.details || {}
}))
class Info extends Component<Props, State> {

  readonly state:State = {
    data: {},
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({ type: 'owner/queryInfo' })
  }

  render() {
    const { details } = this.props;
    
    return (
      <>
        <Details data={details}/>
      </>
    );
  }
}

export default Info;

高阶组件

import React from 'react'

type HOC<InjectedProps, OwnProps = {}> = <P>(
  Component: React.ComponentType<P & InjectedProps>,
) => React.ComponentType<P & OwnProps>

interface IProps {
  primary: string;
  secondary: string;
}

export const withTheme: HOC<IProps> = Component => props => {
  const myTheme: IProps = {
    primary: 'red',
    secondary: 'blue',
  };
  return <Component {...myTheme} {...props} />;
};

export default WithThem;

styled-component

const Card = styled.section<{isNew?: boolean}>`
  color: ${props => props.isNew ? 'red' : 'green'}
`

参考