label.tsx 2.4 KB

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