label.tsx 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import React, { PureComponent } from 'react';
  2. import classNames from 'classnames';
  3. import PropTypes from 'prop-types';
  4. import { cssClasses } from '@douyinfe/semi-foundation/form/constants';
  5. const prefixCls = cssClasses.PREFIX;
  6. export interface LabelProps {
  7. id?: string;
  8. /** Whether to display the required * symbol */
  9. required?: boolean;
  10. /** Content of label */
  11. text?: React.ReactNode;
  12. disabled?: boolean;
  13. /** Used to configure the htmlFor attribute of the label tag */
  14. name?: string;
  15. /** text-align of label */
  16. align?: string;
  17. /** width of label */
  18. width?: number | string;
  19. style?: React.CSSProperties;
  20. className?: string;
  21. children?: React.ReactNode | undefined;
  22. extra?: React.ReactNode;
  23. }
  24. export default class Label extends PureComponent<LabelProps> {
  25. static defaultProps = {
  26. required: false,
  27. name: '',
  28. align: 'left',
  29. className: ''
  30. };
  31. static propTypes = {
  32. id: PropTypes.string,
  33. children: PropTypes.node,
  34. required: PropTypes.bool,
  35. text: PropTypes.node,
  36. disabled: PropTypes.bool,
  37. name: PropTypes.string,
  38. align: PropTypes.string,
  39. width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  40. style: PropTypes.object,
  41. className: PropTypes.string,
  42. extra: PropTypes.node,
  43. };
  44. render() {
  45. const { children, required, text, disabled, name, width, align, style, className, extra, id } = this.props;
  46. const labelCls = classNames(className, {
  47. [`${prefixCls}-field-label`]: true,
  48. [`${prefixCls}-field-label-left`]: align === 'left',
  49. [`${prefixCls}-field-label-right`]: align === 'right',
  50. [`${prefixCls}-field-label-required`]: required,
  51. [`${prefixCls}-field-label-disabled`]: disabled,
  52. [`${prefixCls}-field-label-with-extra`]: extra,
  53. });
  54. const labelStyle = style ? style : {};
  55. width ? labelStyle.width = width : null;
  56. const textContent = (
  57. <div className={`${prefixCls}-field-label-text`}>
  58. {typeof text !== 'undefined' ? text : children}
  59. </div>
  60. );
  61. const contentWithExtra = (
  62. <>
  63. {textContent}
  64. <div className={`${prefixCls}-field-label-extra`}>{extra}</div>
  65. </>
  66. );
  67. return (
  68. <label className={labelCls} htmlFor={name} style={labelStyle} id={id}>
  69. {extra ? contentWithExtra : textContent}
  70. </label>
  71. );
  72. }
  73. }