2019-07-03 20:14:39 +08:00
|
|
|
|
import * as React from 'react';
|
|
|
|
|
import classNames from 'classnames';
|
|
|
|
|
import Col, { ColProps } from '../grid/col';
|
|
|
|
|
import { FormLabelAlign } from './interface';
|
|
|
|
|
import { FormContext, FormContextProps } from './context';
|
|
|
|
|
|
|
|
|
|
export interface FormItemLabelProps {
|
|
|
|
|
colon?: boolean;
|
2019-07-04 15:00:11 +08:00
|
|
|
|
htmlFor?: string;
|
2019-07-03 20:14:39 +08:00
|
|
|
|
label?: React.ReactNode;
|
|
|
|
|
labelAlign?: FormLabelAlign;
|
|
|
|
|
labelCol?: ColProps;
|
|
|
|
|
}
|
|
|
|
|
|
2020-01-17 11:50:06 +08:00
|
|
|
|
const FormItemLabel: React.FC<FormItemLabelProps & { required?: boolean; prefixCls: string }> = ({
|
2019-07-03 20:14:39 +08:00
|
|
|
|
prefixCls,
|
|
|
|
|
label,
|
|
|
|
|
htmlFor,
|
|
|
|
|
labelCol,
|
|
|
|
|
labelAlign,
|
|
|
|
|
colon,
|
|
|
|
|
required,
|
|
|
|
|
}) => {
|
|
|
|
|
if (!label) return null;
|
|
|
|
|
|
|
|
|
|
return (
|
|
|
|
|
<FormContext.Consumer key="label">
|
|
|
|
|
{({
|
|
|
|
|
vertical,
|
|
|
|
|
labelAlign: contextLabelAlign,
|
|
|
|
|
labelCol: contextLabelCol,
|
|
|
|
|
colon: contextColon,
|
|
|
|
|
}: FormContextProps) => {
|
|
|
|
|
const mergedLabelCol: ColProps = labelCol || contextLabelCol || {};
|
|
|
|
|
|
|
|
|
|
const mergedLabelAlign: FormLabelAlign | undefined = labelAlign || contextLabelAlign;
|
|
|
|
|
|
|
|
|
|
const labelClsBasic = `${prefixCls}-item-label`;
|
|
|
|
|
const labelColClassName = classNames(
|
|
|
|
|
labelClsBasic,
|
|
|
|
|
mergedLabelAlign === 'left' && `${labelClsBasic}-left`,
|
|
|
|
|
mergedLabelCol.className,
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
let labelChildren = label;
|
|
|
|
|
// Keep label is original where there should have no colon
|
|
|
|
|
const computedColon = colon === true || (contextColon !== false && colon !== false);
|
|
|
|
|
const haveColon = computedColon && !vertical;
|
|
|
|
|
// Remove duplicated user input colon
|
|
|
|
|
if (haveColon && typeof label === 'string' && (label as string).trim() !== '') {
|
|
|
|
|
labelChildren = (label as string).replace(/[:|:]\s*$/, '');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const labelClassName = classNames({
|
|
|
|
|
[`${prefixCls}-item-required`]: required,
|
|
|
|
|
[`${prefixCls}-item-no-colon`]: !computedColon,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return (
|
|
|
|
|
<Col {...mergedLabelCol} className={labelColClassName}>
|
|
|
|
|
<label
|
|
|
|
|
htmlFor={htmlFor}
|
|
|
|
|
className={labelClassName}
|
|
|
|
|
title={typeof label === 'string' ? label : ''}
|
|
|
|
|
>
|
|
|
|
|
{labelChildren}
|
|
|
|
|
</label>
|
|
|
|
|
</Col>
|
|
|
|
|
);
|
|
|
|
|
}}
|
|
|
|
|
</FormContext.Consumer>
|
|
|
|
|
);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export default FormItemLabel;
|