navSteps.tsx 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import React, { cloneElement, Children, useMemo, isValidElement, ReactElement } from 'react';
  2. import PropTypes from 'prop-types';
  3. import getDataAttr from '@douyinfe/semi-foundation/utils/getDataAttr';
  4. import cls from 'classnames';
  5. import { stepsClasses as css } from '@douyinfe/semi-foundation/steps/constants';
  6. export type Size = 'default' | 'small';
  7. export interface NavStepsProps {
  8. prefixCls?: string;
  9. className?: string;
  10. style?: React.CSSProperties;
  11. current?: number;
  12. initial?: number;
  13. size?: Size;
  14. children?: React.ReactNode;
  15. onChange?: (current: number) => void;
  16. "aria-label"?: string
  17. }
  18. const Steps = (props: NavStepsProps) => {
  19. const { size = 'default', current = 0, initial = 0, children, prefixCls = css.PREFIX, className, style, onChange, ...rest } = props;
  20. const inner = useMemo(() => {
  21. const filteredChildren = Children.toArray(children).filter(c => isValidElement(c)) as Array<ReactElement<any>>;
  22. const total = filteredChildren.length;
  23. const content = Children.map(filteredChildren, (child: React.ReactElement<any>, index) => {
  24. if (!child) {
  25. return null;
  26. }
  27. const childProps = {
  28. index,
  29. total,
  30. ...child.props,
  31. };
  32. childProps.active = index === current;
  33. childProps.onChange = onChange ? () => {
  34. if (index !== current) {
  35. onChange(index + initial);
  36. }
  37. } : undefined;
  38. return cloneElement(child, { ...childProps });
  39. });
  40. return content;
  41. }, [children, prefixCls, current, size, initial, onChange]);
  42. const wrapperCls = cls(className, {
  43. [`${prefixCls}-nav`]: true,
  44. [`${prefixCls}-${size}`]: size !== 'default',
  45. });
  46. return (
  47. <div aria-label={props["aria-label"]} className={wrapperCls} style={style} {...getDataAttr(rest)}>
  48. {inner}
  49. </div>
  50. );
  51. };
  52. export default Steps;