-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathindex.tsx
31 lines (26 loc) · 950 Bytes
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import dayjs from 'dayjs';
import { ago, AgoValue } from '../utils/ago';
export interface AgoProps
extends React.HTMLProps<HTMLSpanElement | HTMLDivElement> {
// 将要格式化显示的日期,任意的dayjs识别的格式
date?: dayjs.ConfigType;
// 是否显示为块div,默认为span
block?: boolean;
// 定制内容
renderContent?: (result: AgoValue) => React.ReactNode;
}
export function Ago(props: AgoProps) {
const { date = dayjs(), block = false, renderContent, ...attrs } = props;
const agoValue = ago(date);
// 格式化内容
let content: string | React.ReactNode = agoValue.format;
if (typeof renderContent === 'function') {
content = renderContent(agoValue);
}
// 是否显示为块元素
if (block) {
return <div {...(attrs as React.HTMLProps<HTMLDivElement>)}>{content}</div>;
}
// 默认显示行内元素
return <span {...attrs}>{content}</span>;
}