3 回答
TA贡献1788条经验 获得超4个赞
class App extends Component{
constructor(props){
super(props);
this.state={
arr:[],
index:0
}
this.handle=null;
this.stopClickHandle=this.stopClickHandle.bind(this);
}
stopClickHandle(){
if(this.handle){
clearInterval(this.handle);
this.handle=null;
}
}
componentDidMount(){
const me=this;
this.handle=setInterval(function(){
me.setState(function(preState){
let arr=[preState.index++,...preState.arr];
return {arr};
});
if(me.state.index == me.props.max){
me.stopClickHandle();
}
},1000);
}
render(){
let arr=this.state.arr;
arr=arr.map(function(item){
return (<div>{item}</div>)
});
return(
<div>
{arr}
</div>
)
}
}
ReactDOM.render(<App max={5} />,document.body);
TA贡献1880条经验 获得超4个赞
import React from "react";
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {arr:["div"]};
}
componentDidMount() {
this.timeID = setInterval(
()=> this.tick(),
1000
)
}
componentWillUnmount(){
clearInterval(this.timeID)
}
tick() {
// 5 个 停止计时器
if(this.state.arr.length ===5) {
clearInterval(this.timeID);
return;
}
this.setState((prevState,props) => ({
arr:[...prevState.arr,props.add]
}))
}
render(){
return (
this.state.arr.map((item,idx)=> (
<div>
<h1>{item}</h1>
</div>
))
)
}
}
ReactDOM.render(
<Clock add={"div"}/>,
document.getElementById('root')
);
添加回答
举报