让前端飞

向Button.Group一样的使用组件

2020-07-05  本文已影响0人  小遁哥
<Title color="red">1</Title>
<Title.Level color="red">12</Title.Level>

class组件中

Title.Level

import React from 'react';
interface levelProps {
  color: string;
}
interface levelState {}
class level extends React.PureComponent<levelProps, levelState> {
  constructor(props: levelProps) {
    super(props);
    this.state = {};
  }
  public render() {
    const { children, color } = this.props;
    return (
      <>
        <h1 style={{ color }}> {children}</h1>
      </>
    );
  }
}

export default level;

Title

import React from 'react';
import level from './level';
interface TitleProps {
  color: string;
}
interface TitleState {}

class Title extends React.PureComponent<TitleProps, TitleState> {
  static Level: typeof level;
  constructor(props: TitleProps) {
    super(props);
    this.state = {};
  }
  public render() {
    const { color } = this.props;
    return (
      <>
        <div style={{ color }}>1</div>
      </>
    );
  }
}
Title.Level = level;
export default Title;

注意static Level: typeof level;

在函数式组件中

Title.Level

import * as React from 'react';
export interface LevelProps {
  color: string;
}
const Level: React.FC<LevelProps> = (props, ref) => {
  const { children, color } = props;
  return <h1 style={{ color }}>{children}</h1>;
};

export default Level;

Title

import * as React from 'react';
import Level from './Level';

export interface TitleProps {
  color?: string;
  children?: any;
}

const Title: React.FC<TitleProps> & { Level: typeof Level } = (
  props,
) => {
  const { children, color } = props;
  return <div style={{ color }}>{children}</div>;
};

Title.defaultProps = {
  color: 'red',
};
Title.Level = Level;
export default Title;

注意 <TitleProps> & { Level: typeof Level }

当被 forwardRef 包裹后

Title.Level

import * as React from 'react';
export interface LevelProps {
  color: string;
}
const Level: React.FC<LevelProps> = (props, ref) => {
  const { children, color } = props;
  return <h1 style={{ color }}>{children}</h1>;
};

export default Level;

Title

import * as React from 'react';
import Level from './Level';
export interface TitleProps {
  color?: string;
  children?: React.ReactNode;
}
interface ComposeTitle
  extends React.ForwardRefExoticComponent<
    TitleProps & React.RefAttributes<React.ReactNode>
  > {
  Level: typeof Level;
}
const InnerTitle: React.ForwardRefRenderFunction<
  unknown,
  TitleProps
> = (props, ref) => {
  const { children, color } = props;
  return <div style={{ color }}>{children}</div>;
};

export const Title = React.forwardRef<unknown, TitleProps>(
  InnerTitle,
) as ComposeTitle;
Title.defaultProps = {
  color: 'red',
};
Title.Level = Level;

可以参照antd3.x、4.x的源码

上一篇 下一篇

猜你喜欢

热点阅读