有没有办法在外部传递函数内部的变量 [英] is there a way to pass variable inside of a function outside in react

查看:71
本文介绍了有没有办法在外部传递函数内部的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to react, and I am trying to make a simple countdown app. but in react, I don't know how to give a global variable for all the functions can get assess to it. Please take a look at my code, is there anyway I can make the pause and the continue buttons work? In plain javascript I can set timer as a global variable and get access to it from another function, by that, I can call clearInterval on timer when I want, but in react I don't know how to call clearInterval for timer to pause begin function since it is restricted in the begin function block.

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

推荐答案

您可以这样做:

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

工作代码此处

这篇关于有没有办法在外部传递函数内部的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆