javascript 如何使用React显示工作的数字时钟

lnvxswe2  于 2023-01-16  发布在  Java
关注(0)|答案(7)|浏览(156)

我想在浏览器上呈现数字时钟,我不知道在我的脚本中在哪里使用setInterval()函数,也不知道用作第一个参数的函数的名称是什么。

<!DOCTYPE html>
    <html>
    <head>
        <title>My First App</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
    </head>
    <body>
    <div id="react-app"></div>
    <div id="clock-box"></div>

    <script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react.js"></script>
    <script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react-dom.js"></script>

    <script type="text/jsx">

    class StoryBox extends React.Component{
            render(){
                return(<div> Hello World </div> );
            }
        }
    var target= document.getElementById('react-app');
    var clockTarget=document.getElementById('clock-box');
    ReactDOM.render(<StoryBox/>,target)

    class ClockFunction extends React.Component{
        render(){
            return(<div>
                <h1>Digital Clock</h1>
                <h2>
                {
                    new Date().toLocaleTimeString() 
                    }
                </h2>
            </div>) ;
        }
    }

    ReactDOM.render(<ClockFunction />,clockTarget);

    </script>

    </body>
    </html>
lrpiutwd

lrpiutwd1#

为此,您需要一些东西:

  1. setInterval,用于更新时间
    1.组件的state中用于跟踪时间的变量
    1.分别在组件挂载和卸载时添加和删除setInterval的安全方法
    此组件将执行所有这些操作:
class ClockFunction extends React.Component {

    constructor() {
        super();
        this.state = { time: new Date() }; // initialise the state
    }

    componentDidMount() { // create the interval once component is mounted
        this.update = setInterval(() => {
            this.setState({ time: new Date() });
        }, 1 * 1000); // every 1 seconds
    }

    componentWillUnmount() { // delete the interval just before component is removed
        clearInterval(this.update);
    }

    render() {
        const { time } = this.state; // retrieve the time from state

        return (<div>
            <h1>Digital Clock</h1>
            <h2>
                {/* print the string prettily */}
                {time.toLocaleTimeString()}
            </h2>
        </div>);
    }
}
6kkfgxo0

6kkfgxo02#

import React, { Component } from "react";

class Clock extends Component {
    constructor (props) {
        super(props);

        this.state = {
            dateClass: new Date()
        }

        this.time = this.state.dateClass.toLocaleTimeString();
        this.hourMin = this.time.length === 10? this.time.slice(0) : this.time.slice(0,5);
    }

    setTime = () => {
        this.setState({
            dateClass: new Date()
        })
        this.time = this.state.dateClass.toLocaleTimeString();
        this.hourMin = this.time.length === 10? this.time.slice(0) : this.time.slice(0,5);
    }

    componentDidMount () {
        setInterval(this.setTime, 1000)
    }
    
    render () {
        return (
            <div>
                {this.hourMin}
            </div>
        )
    }
}

export default Clock;

也许你可以试试这种方法。

vcirk6k6

vcirk6k63#

class ClockFunction extends React.Component{
    //setInterval and setState go in component Did mount
    componentDidMount (){
    this.setState({time : (new Date()).getTime()}
    // update every second
    this.tick = setInterval( () => this.setState(time : this.state.time + 1000, 1000)
    }

    //use state to display time in render function
    render(){
        return(<div>
            <h1>Digital Clock</h1>
            <h2>
            {
                this.state.time
            }
            </h2>
        </div>) ;
    }
}
ilmyapht

ilmyapht4#

//一个非常简单的React数字时钟

class App extends React.Component {
        componentDidMount() {
            setInterval(() => {
                this.getTime();
            })
        }
        constructor() {
            super();
            this.state = {
                time: "00:00:00:AM",
            }
        }
        getTime() {
            setInterval(() => {
                let date = new Date();
                let hour = date.getHours();
                let minute = date.getMinutes();
                let seconds = date.getSeconds();
                let ampm = this.hour >= 12 ? 'AM' : 'PM';
                hour = hour % 12;
                hour = hour ? hour : 12;
                hour = fullTime(hour);
                minute = fullTime(minute);
                seconds = fullTime(seconds); 
                this.setState({
                    time: hour % 12 + ":" + minute + ":" + seconds + ":" + 
                 ampm,
                });
                function fullTime(n) { return n < 10 ? "0" + n : n }

            }, 1000);
        }
        render() {
            return (
                <div className="container">
                    <h3>{this.state.time}</h3>
                </div>
            );
        }
    };

    ReactDOM.render(<App />, document.querySelector("#root"));
hmmo2u0o

hmmo2u0o5#

const MyClock = () => {
  const [time, setTime] = useState(new Date());
   useEffect(() => {
     let TimeId = setInterval(() => setTime(new Date()), 1000);
     return () => {
      clearInterval(TimeId);
     };
     });

      return <div > itis {
          time.toLocaleTimeString()
  } < /div>;
 };
zpgglvta

zpgglvta6#

在几个步骤内,我们可以轻松地显示数字时钟,让我们使用类组件和返回时间的toLocaleTimeString()方法。
我们开始

import React from 'react'

class Clock extends React.Component{
     state = {time: ''};
     componentDidMount(){
          setInterval(
          () => this.setState({time: new Date().toLocaleTimeString()},1000)
          )

    }
    render(){
        return(
            <div>{this.state.time}</div>
        )
    }
}
dfuffjeb

dfuffjeb7#

使用react钩子:

import {useEffect, useState} from "react";

export default function Clock() {

const [time, setTime] = useState(new Date().toLocaleTimeString())

useEffect(() => {
    const id = tick()
    return () => clearTimeout(id)
}, [])

const tick = () => {
    return setInterval(() => {
        setTime(() => new Date().toLocaleTimeString())
    }, 1000)
}

return (
    <p>Current time: {time}</p>
)

}

相关问题