问题
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'));
回答1:
You can do like this:
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'));
working code here
回答2:
Why not declare the begin inside the react component. You will also need to update the state when the count down begins. I recommend you take a look at https://reactjs.org/tutorial/tutorial.html.
来源:https://stackoverflow.com/questions/47524587/is-there-a-way-to-pass-variable-inside-of-a-function-outside-in-react