有没有办法在react外部的函数内部传递变量

IT技术 reactjs global-variables continue pause
2021-05-10 07:16:12

我是新手,我正在尝试制作一个简单的倒计时应用程序。但是在react中,我不知道如何为所有可以对其进行评估的函数提供全局变量。请看一下我的代码,无论如何我可以使暂停和继续按钮起作用吗?在普通的 javascript 中,我可以将计时器设置为全局变量并从另一个函数访问它,这样,我可以在需要时在计时器上调用 clearInterval,但作为react,我不知道如何调用 clearInterval 来让计时器暂停开始功能,因为它在开始功能块中受到限制。

import React from 'react';
import ReactDOM from 'react-dom';

class Countdown extends React.Component{
    render(){
        return(
            <div>
                <button onClick={()=>begin()}>start</button>
                <button>pause</button>
                <button>continue</button>
            </div>
        );
    }
};

const begin=(props)=>{
    let count = 10;
    const timer = setInterval(countdown,1000);
    function countdown(){
        count=count-1
        if (count<0){
            clearInterval(timer);
            return; 
        }
        console.log(count)
    }
}

ReactDOM.render(<Countdown/>, document.getElementById('app'));
2个回答

你可以这样做:

class Countdown extends React.Component{
    constructor() {
        super();
        //set the initial state
        this.state = { count: 10 };
    }
    //function to change the state
    changeCount(num){
      this.setState({count:num});
    }
    render(){
        return(
            <div>
                <button onClick={()=>begin(this.changeCount.bind(this), this.state.count)}>start</button>
                <button>pause</button>
                <button>continue</button>
                <p>{this.state.count}</p>
            </div>
        );
    }
};
//callback function to change the state in component
//c is the initial count in state
const begin=(fun, c)=>{
    let count = c;
    const timer = setInterval(countdown,1000);
    function countdown(){
        count=count-1
        if (count<0){
            clearInterval(timer);
            return; 
        }
        fun(count)
        console.log(count)
    }
}

ReactDOM.render(<Countdown/>, document.getElementById('example'));

工作代码在这里

为什么不在react组件中声明开始。您还需要在倒计时开始时更新状态。我建议您查看https://reactjs.org/tutorial/tutorial.html