我是React / React Native的新手,我正在尝试制作一个从0到100的函数,并以图形仪表显示它。模拟从0到100 MPH的速度计。因此,这是我的 onPress 函数,如果按下该函数,该函数将计数一次:
import React, { Component } from 'react';
import {
StyleSheet,
TouchableOpacity,
Text,
View,
} from 'react-native';
import Speedometer from 'react-native-speedometer-chart';
export default class App extends Component {
constructor(props) {
super(props)
this.state = { count: 0 }
}
onPress = () => {
this.setState({
count: this.state.count+1
})
}
然后,我添加了一条while语句,如果 count 小于100,它将继续上升。问题在于它不算数。
onPress = () => {
while(this.state.count < 100) {
this.setState({
count: this.state.count+1
})
}
}
有人可以帮忙吗?这是我的完整代码:
import React, { Component } from 'react';
import {
StyleSheet,
TouchableOpacity,
Text,
View,
} from 'react-native';
import Speedometer from 'react-native-speedometer-chart';
export default class App extends Component {
constructor(props) {
super(props)
this.state = { count: 0 }
}
onPress = () => {
while(this.state.count <= 100) {
this.setState({
count: this.state.count+1
})
}
}
clear = () => {
this.setState({
count: this.state.count = 0
})
}
render() {
return (
<View style={styles.container}>
<Text style={styles.titleText}> AlphaDyne New Run Screen</Text>
<TouchableOpacity style={styles.button} onPress={this.onPress}>
<Text> Start Run </Text>
</TouchableOpacity>
<View style={[styles.countContainer]}>
<Speedometer
value={this.state.count !== 0 ? this.state.count: 0}
totalValue={100}
size={250}
outerColor="#d3d3d3"
internalColor="#ff0000"
showText
text="MPH"
textStyle={{ color: '#ff0000' }}
showLabels
labelStyle={{ color: '#FF00FF' }}
/>
<Text style={styles.countText}>{this.state.count !== 0 ? this.state.count: 0} MPH</Text>
<Text style={styles.space}></Text>
<Speedometer
value={this.state.count !== 0 ? this.state.count: 0}
totalValue={100}
size={250}
showIndicator
showLabels
labelStyle={{ color: '#FF00FF' }}
/>
<Text style={styles.countText}>{this.state.count !== 0 ? this.state.count: 0} MPH</Text>
<Text style={styles.spacer}></Text>
<Text style={styles.spacer}></Text>
<TouchableOpacity style={styles.button} onPress={this.clear}>
<Text> Clear </Text>
</TouchableOpacity>
</View>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingHorizontal: 10
},
button: {
alignItems: 'center',
backgroundColor: '#DDDDDD',
padding: 10
},
countContainer: {
alignItems: 'center',
padding: 10,
marginTop: 20
},
countText: {
color: '#FF00FF',
fontSize: 20,
marginTop: 10
},
titleText: {
fontSize: 30,
alignSelf: 'center',
marginBottom: 20
},
space: {
marginTop: 20
}
});
谢谢!
答案 0 :(得分:0)
您必须调用函数setState来克服解决方案中的异步性问题:
onPress = () => {
while(this.state.count <= 100) {
this.setState(previousState => ({ ...previousState, count: previousState.count + 1 }));
}
}