如何用 REACT 制作一个滴答作响的时钟
大家好!在本文中,我们将使用 React 构建一个数字滴答时钟,很酷吧?:)
React 和数字时钟的快速介绍:
反应
React是由 Facebook 创建的 JavaScript 库
React是一个用户界面(UI)库
React是一个用于构建 UI 组件的工具
数字时钟
数字时钟是一种以数字(即数字或其他符号)显示时间的时钟,与模拟时钟相反,模拟时钟通过旋转指针的位置指示时间。
现在我们将开始创建一个 React 应用程序,转到窗口终端上您选择的任何目录,然后在命令提示符下键入以下内容。
npx create-react-app ticking-clock-with-react
安装成功后更改目录
cd ticking-clock-with-react
启动 React 应用程序
npm start
您应该会在浏览器中看到此信息。不用担心,这可能需要几分钟。
快乐黑客!
现在,让我们在您选择的任何 IDE 中打开我们的应用程序,我使用Visual Studio Code进行开发,您也可以随意使用您选择的任何 IDE。
您应该看到如下所示的文件结构:
在 App.js 中,我们需要将其从函数式组件更改为基于类的组件。如果您没有类组件,则应该看到类似下面的屏幕截图,请跳过此步骤。
import React, { Component } from 'react';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<div className="clock">
</div>
</div>
);}
}
export default App;
然后你的 App.css 应该有类似下面的截图
.App {
text-align: center;
}
.clock {
background-color: #282c34;
min-height: 100vh;
align-items: center;
justify-content: center;
}
现在让我们创建名为 clock.js 和 clock.css 的时钟组件,以便在 src 文件夹中设置其样式。
将下面的代码片段插入之前创建的clock.js组件中。
import React, { Component } from 'react';
class Clock extends Component {
constructor(props){
super(props);
//This declared the state of time at the very beginning
this.state ={
time: new Date().toLocaleTimeString()
}
}
//This happens when the component mount and the setInterval function get called with a call back function updateClock()
componentDidMount() {
this.intervalID = setInterval(() =>
this.updateClock(),
1000
);}
//This section clears setInterval by calling intervalID so as to optimise memory
componentWillUnmount(){
clearInterval(this.intervalID)
}
//This function set the state of the time to a new time
updateClock(){
this.setState({
time: new Date().toLocaleTimeString()
});
}
render() {
return (
<div className="Time">
<p> {this.state.time}</p>
</div>
);}
}
export default Clock;
现在,您需要在 App.js 文件中从 './clock'; 导入 Clock,以便在 Web 浏览器中查看时钟。参见下方截图
在clock.css文件中添加以下代码片段:
.Time {
height: 500px;
width: 800px;
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
padding-top: 70px;
font-family: courier, monospace;
color: white;
font-size: 110px;
}
现在您需要在clock.js中导入'./clock.css';如下所示:
在你的浏览器上你应该看到这个
你的 App.js 应该有这个:
import React, { Component } from 'react';
import Clock from './clock';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<div className="clock">
<Clock />
</div>
</div>
);
}
}
export default App;
最后:我们的时钟滴答作响,运转完美:)
不要忘记为该 repo 加星标并在这里竖起大拇指!!!
谢谢你!
鏂囩珷鏉ユ簮锛�https://dev.to/olanetsoft/how-to-build-a-ticking-clock-with-react-425f