我正在尝试制作一个简单的时钟,它可以在按下按钮时启动和停止。在这里,我设置了一个等于 setInterval 的变量,以便稍后清除它。但是由于某种原因,它在没有按下按钮的情况下被调用。
这里 autoInc 应该在我按下“开始”按钮时被理想地调用,但它无论如何都会被调用。
import React, { Component } from "react";
import { Text, View, Button } from "react-native";
export default class Counter extends Component {
increaser = () => {
this.setState(prePre => {
return { counter: prePre.counter + 1 };
});
};
constructor(props) {
super(props);
this.state = {
counter: 0,
wantToShow: true
};
autoInc = setInterval(this.increaser, 1000);
}
render() {
if (this.state.wantToShow)
return (
<View>
<Text style={{ color: "red", fontSize: 50, textAlign: "center" }}>
{this.state.counter}
</Text>
<Button title="Start" onPress={this.autoInc} />
</View>
);
}
}
最佳答案
这里有一个完整的 react
示例,您只需在 react native 中翻译函数即可。
在你的构造函数中创建一个变量 this.interval=null
,在 startFn
中给它分配间隔,然后用 window.clearInterval( this.interval);
export default class App extends Component {
constructor(props) {
super(props);
this.interval = null;
}
componentDidMount() {}
startFn = () => {
console.log("assign and start the interval");
this.interval = setInterval(this.callbackFn, 1000);
};
stopFn = () => {
console.log("clear interval");
window.clearInterval(this.interval);
};
callbackFn = () => {
console.log("interval callback function");
};
render(props, { results = [] }) {
return (
<div>
<h1>Example</h1>
<button onClick={this.startFn}>start Interval</button>
<button onClick={this.stopFn}>stop Interval</button>
</div>
);
}
}
此处的 Codesandbox 示例:https://codesandbox.io/s/j737qj23r5
关于javascript - 为什么在 react native 中自动调用 setInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53150168/