我正在尝试创建一个小程序,其中必须使用react JS显示日期和时间。它会按预期显示HTML页面中除日期和时间值以外的所有内容。
enter code here
import React from "react";
import ReactDOM from "react-dom";
const name = "Flash";
const currDate = new Date().toLocaleDateString;
const currTime = new Date().toLocaleTimeString;
ReactDOM.render(
<>
<h1>My name is {name}</h1>
<p> Current Date is = {currDate} </p>
<p> Curremt Time is = {currTime} </p>
</>,
document.getElementById("root"));
答案 0 :(得分:0)
所有内容在您的代码中都是完美的,但是您只是忘记运行这些功能。
toLocaleDateString
和toLocaleTimeString
不仅仅是对象,因此您需要添加括号以运行这些函数并获取结果。
所以替换掉它:
const currDate = new Date().toLocaleDateString;
const currTime = new Date().toLocaleTimeString;
与此:-
const currDate = new Date().toLocaleDateString();
const currTime = new Date().toLocaleTimeString();
所以您的最终代码变为:-
import React from "react";
import ReactDOM from "react-dom";
const name = "Flash";
const currDate = new Date().toLocaleDateString();
const currTime = new Date().toLocaleTimeString();
ReactDOM.render(
<>
<h1>My name is {name}</h1>
<p> Current Date is = {currDate} </p>
<p> Curremt Time is = {currTime} </p>
</>,
document.getElementById("root"));
答案 1 :(得分:0)
在Reactjs中获取当前日期的简单分步指南
import React from 'react';
import logo from './logo.svg';
import './App.css';
class App extends React.Component {
state={
curTime : new Date().toLocaleString(),
}
render(){
return (
<div className="App">
<p>Current Time : {this.state.curTime}</p>
</div>
);
}
}
export default App;