label.tsx 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. extra?: React.ReactNode;
  22. }
  23. export default class Label extends PureComponent<LabelProps> {
  24. static defaultProps = {
  25. required: false,
  26. name: '',
  27. align: 'left',
  28. className: ''
  29. };
  30. static propTypes = {
  31. id: PropTypes.string,
  32. children: PropTypes.node,
  33. required: PropTypes.bool,
  34. text: PropTypes.node,
  35. disabled: PropTypes.bool,
  36. name: PropTypes.string,
  37. align: PropTypes.string,
  38. width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  39. style: PropTypes.object,
  40. className: PropTypes.string,
  41. extra: PropTypes.node,
  42. };
  43. render() {
  44. const { children, required, text, disabled, name, width, align, style, className, extra, id } = this.props;
  45. const labelCls = classNames(className, {
  46. [`${prefixCls}-field-label`]: true,
  47. [`${prefixCls}-field-label-left`]: align === 'left',
  48. [`${prefixCls}-field-label-right`]: align === 'right',
  49. [`${prefixCls}-field-label-required`]: required,
  50. [`${prefixCls}-field-label-disabled`]: disabled,
  51. [`${prefixCls}-field-label-with-extra`]: extra,
  52. });
  53. const labelStyle = style ? style : {};
  54. width ? labelStyle.width = width : null;
  55. const textContent = (
  56. <div className={`${prefixCls}-field-label-text`}>
  57. {typeof text !== 'undefined' ? text : children}
  58. </div>
  59. );
  60. const contentWithExtra = (
  61. <>
  62. {textContent}
  63. <div className={`${prefixCls}-field-label-extra`}>{extra}</div>
  64. </>
  65. );
  66. return (
  67. <label className={labelCls} htmlFor={name} style={labelStyle} id={id}>
  68. {extra ? contentWithExtra : textContent}
  69. </label>
  70. );
  71. }
  72. }