网站搜索

javascript - React-Typescript:我找不到我的 getCurrentTime 函数为什么不能工作的原因


我正在尝试编写一个函数来显示当前时间与例如消息创建时间之间的时间差。为此,我编写了一个函数来在进行下一步之前获取我当前的时间。

我打算将结果放入表格中,使用 <td>{getCurrentTime}</td>,但是我看不到该函数的任何结果显示。甚至第二列都没有出现。

import React from "react";

export function getCurrentTime () {
    let today = new Date();
    let dateTime = (today.getHours() < 10 ? '0' : '') + ':' + (today.getMinutes() < 10 ? '0' : '') + ':' + (today.getSeconds() < 10 ? '0' : '');
    return dateTime;
}

//console.log(getCurrentTime);

export default getCurrentTime

这是我想要显示时间的地方:

const CommitMsgTable = ({ apiCommitsResponse }: CommitMsgTableProps) => {
let colorToggle = false;
return <div><table>{apiCommitsResponse.map(commit => {
    colorToggle = !colorToggle;
    return (
        <tr>
            <td>{getCurrentTime}</td>
            <td style={{ backgroundColor: colorToggle ? "lightgrey" : "white" }}>                
                {commit}
            </td>
        </tr>)
})}
</table></div>

由 tanmay 和 El Pandario 解决!我在表格数据中调用 {getCurrentTime} 后忘记加括号()

答案#1

类似这样的东西应该可以工作:

export default function App() {
  return (
    <div className="App">
      <tr>
        <td>Time: {getCurrentTime()}</td>
      </tr>
    </div>
  );
}

export function getCurrentTime () {
  let today = new Date();
  let dateTime = (today.getHours() < 10 ? `0${today.getHours()}` : `${today.getHours()}`) + ':' + (today.getMinutes() < 10 ? `0${today.getMinutes()}` : `${today.getMinutes()}`) + ':' + (today.getSeconds() < 10 ? `0${today.getSeconds()}` : `${today.getSeconds()}`);
  console.log(dateTime);
  return dateTime;
}

答案#2

我不明白你的意思,但我想你是想要类似这样的东西:

const getCurrentTime = () => {
    const date = new Date();
    const hours = date.getHours();
    const minutes = date.getMinutes();
    const seconds = date.getSeconds();
    const timeString = `${hours.toString().length === 1 ? `0${hours}` : hours}:${minutes.toString().length === 1 ? `0${minutes}` : minutes}:${seconds.toString().length === 1 ? `0${seconds}` : seconds}`;
    return timeString;
};

console.log(getCurrentTime())