【发布时间】:2022-01-12 22:09:59
【问题描述】:
我正在使用以下代码设置 Luxon 时钟以供我的项目使用。
import { DateTime } from 'luxon';
import React, { useEffect, useState } from 'react';
interface IProps {
timezone: string;
format: string;
calendar?: string;
daysOffset?: number;
}
const LiveDateTime: React.FC<IProps> = ({
timezone,
daysOffset,
format,
calendar,
}) => {
const [timeLive, setTimeLive] = useState<DateTime>(DateTime.local());
useEffect(() => {
const interval = setInterval(() => {
setTimeLive(
DateTime.local()
.setZone(timezone)
.reconfigure({ outputCalendar: calendar })
.plus({ days: daysOffset })
);
}, 1000);
return () => clearInterval(interval);
}, [timezone]);
return <span>{timeLive?.toFormat(format)}</span>;
};
export default LiveDateTime;
现在,我在另一个地方使用这个组件来定义当前日期的月份#。
const month = <LiveDateTime timezone={place?.timezone} format="M" />; // This returns '12' as a number in the UI (for December)
console.log(month)
getData(month); //this functions is supposed to return some data based on the given month.
//I get an error instead on this line that says, 'Argument of type 'Element' is not assignable to parameter of type 'number'.
当我在控制台中打印它时,我得到了一个完整的 react.element 对象。我需要能够在getData()month 变量中使用“12”作为数字(12 月)。 如果需要,如何将此对象转换为数字类型或字符串类型?
附言我尝试使用 pareInt()。不工作。
【问题讨论】:
-
您不应该仅仅为了转换时间而返回组件。有很多图书馆已经完成了这项工作,例如
date-fns, luxon, moment。请随意选择适合您用例的那个,然后在组件本身中转换时间,而不是创建一个组件来转换时间。
标签: javascript reactjs typescript next.js luxon