首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >反应型记录:我没有发现为什么我的getCurrentTime函数不能工作的问题

反应型记录:我没有发现为什么我的getCurrentTime函数不能工作的问题
EN

Stack Overflow用户
提问于 2022-04-29 09:00:07
回答 2查看 57关注 0票数 2

我试图编写一个函数来显示当前时间与消息创建时间之间的差异时间。因此,在进入下一步之前,我编写了一个函数来获得当前的时间。

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

代码语言:javascript
复制
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

这就是我想要展示的时间:

代码语言:javascript
复制
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>

由坦梅和埃尔·潘达里奥解决!在表数据中调用{getCurrentTime}后,忘记了方括号()

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-04-29 09:48:39

像这样的事情应该有效:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2022-04-29 09:14:57

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

代码语言:javascript
复制
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())

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72055399

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档