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

时间:2017-07-05 07:53:53

标签: javascript reactjs dom

我想在浏览器上渲染数字时钟,我不知道在我的脚本中使用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>

4 个答案:

答案 0 :(得分:3)

为此,你需要做一些事情:

  1. setInterval更新时间
  2. 组件state中用于跟踪时间的变量
  3. 分别安装和卸载组件时添加和删除setInterval的安全方法
  4. 这个组件将完成所有这些事情:

    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>);
        }
    }
    

答案 1 :(得分:1)

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;

也许您可以尝试这种方法。

答案 2 :(得分:0)

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>) ;
    }
}

答案 3 :(得分:0)

//一个非常简单的React Digital时钟

    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"));