【问题标题】:is there a way to pass variable inside of a function outside in react有没有办法在反应外部的函数内部传递变量
【发布时间】:2018-05-11 11:56:42
【问题描述】:

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

【问题讨论】:

  • 这肯定会有所帮助,因为它与您的情况相同,reactjs.org/docs/state-and-lifecycle.html
  • 谢谢,我在使用 clearInterval 时确实遇到了麻烦,因为我无法访问 begin 函数内的计时器。在 Javascript vanilla 中,我可以将计时器声明为全局变量,然后在任何地方都可以访问它,但在反应中我无法做到这一点。

标签: reactjs global-variables continue pause


【解决方案1】:

你可以这样做:

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

【讨论】:

  • 谢谢,您知道如何访问计时器,以便我可以调用 clearInterval() 来执行暂停功能吗?
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 2020-08-13
    • 1970-01-01
    相关资源
    最近更新 更多