我刚刚学习了本机响应,并且正在尝试学习如何从https://www.npmjs.com/package/react-native-swipe-gestures实现滑动手势,但是关于this.setstate不是函数存在错误。我该如何解决这个问题?我尝试将计数器增加1的方式有问题吗?
import React, {Component} from 'react';
import {
View,
Text,
SafeAreaView,
TouchableOpacity,
Image,
ScrollView,
StyleSheet,
} from 'react-native';
import Speaker from '../../img/flashcard/Speaker.png';
import GestureRecognizer, {swipeDirections} from 'react-native-swipe-gestures';
import Sound from 'react-native-sound';
//cards
import letter from '../../img/flashcard/c/letter.png';
import cow from '../../img/flashcard/c/cow.png';
import SwipeButton from 'rn-swipe-button';
//sounds
const styles = StyleSheet.create({
card: {
width: 345,
height: 480,
borderRadius: 50,
marginTop: 34,
},
text: {fontSize: 30, fontFamily: 'Arial', color: 'grey'},
speaker: {
width: 86,
height: 76,
marginTop: 44,
},
});
export default class flashcardC extends React.Component {
state = {
counter: 1,
imagecount: 10,
imagesource: 'letter',
soundsource: '',
};
updateImgsrc() {
switch (this.state.imagesource) {
case 1:
return letter;
case 2:
return cow;
}
}
onSwipeLeft(gestureState) {
this.setState(prevState => ({counter: prevState.counter + 1}));
this.setState({imagesource: this.state.counter});
}
onSwipeRight(gestureState) {
this.setState(prevState => ({counter: prevState.counter + 1}));
this.setState({imagesource: this.state.counter});
}
render() {
const config = {
velocityThreshold: 0.3,
directionalOffsetThreshold: 80,
};
return (
<SafeAreaView>
<View style={{marginTop: 28, alignItems: 'center'}}>
<Text style={styles.text}>
{this.state.counter}/{this.state.imagecount}
</Text>
<GestureRecognizer
onSwipeLeft={this.onSwipeLeft}
onSwipeRight={this.onSwipeRight}
config={config}>
<Image src={this.updateImgsrc()} style={styles.card} />
</GestureRecognizer>
<Image source={Speaker} style={styles.speaker} />
</View>
</SafeAreaView>
);
}
}
答案 0 :(得分:0)
我认为这是因为存在绑定问题。尝试将所有功能编写为箭头功能。
onSwipeLeft = () => {
this.setState(prevState => ({ counter: prevState.counter + 1 }));
this.setState({ imagesource: this.state.counter });
};
onSwipeRight = () => {
this.setState(prevState => ({ counter: prevState.counter + 1 }));
this.setState({ imagesource: this.state.counter });
};
希望它对您有帮助。