有没有办法在反应之外的函数内部传递变量

is there a way to pass variable inside of a function outside in react

我是反应新手,正在尝试制作一个简单的倒计时应用程序。但在反应中,我不知道如何为所有可以评估的函数提供一个全局变量。请看看我的代码,无论如何我可以让暂停和继续按钮工作吗?在普通 javascript 中,我可以将计时器设置为全局变量并从另一个函数访问它,这样,我可以在需要时调用计时器上的 clearInterval,但在反应中我不知道如何调用 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'));

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

你可以这样做:

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

工作代码here