我正在研究此组件,无法找到使scrollViewRef
在setInterval
内部工作的方法。我尝试同时使用scrollViewRef
和scrollViewRef.current
,但是给出undefined不是对象。我相信onpress
之后可以看到模式,因此scrollViewRef
不会在setInterval
内部进行更新。
const App = () => {
let interval;
let scrollViewRef = useRef(null);
const imageRef = useRef(null);
const [x, setX] = useState(1);
const [modalVisible, setModalVisible] = useState(false);
const [top, setTop] = useState('#87cefa');
const [left, setLeft] = useState('#cdcdcd');
const [right, setRight] = useState('#cdcdcd');
const [bottom, setBottom] = useState('#cdcdcd');
const [imageSize, setImageSize] = useState({});
useEffect(() => {
// console.log(scrollViewRef);
Image.getSize(
'https://jjj.s3.ap-south-1.amazonaws.com/1/out8.jpeg',
(width, height) => {
setImageSize({
imageWidth: width,
imageHeignt: height,
quadrantSize: Math.round(width / 4),
});
}
);
}, []);
const onBackPress = () => {
clearInterval(interval);
// SoundPlayer.stop();
setModalVisible(false);
setX(1);
setTop('#87cefa');
setLeft('#cdcdcd');
};
const onPress = () => {
setModalVisible(true);
// SoundPlayer.playSoundFile('aaa', 'mp3');
interval = setInterval(() => {
scroll(x);
}, 50);
};
const scroll = (x) => {
const quadrantSize2 = imageSize.quadrantSize * 2;
const quadrantSize3 = imageSize.quadrantSize * 3;
const quadrantSize4 = imageSize.quadrantSize * 4;
// countRef.current.scrollTo({ x: 8, animated: true });
setTimeout(() => {
console.log('uhuihiuh');
scrollViewRef.current.scrollTo({ x: 8, animated: true });
}, 50);
if (x === imageSize.imageWidth) {
clearInterval(interval);
setTimeout(() => {
onBackPress();
}, 1000);
} else {
setX(x + 1);
}
if (x <= imageSize.quadrantSize && x >= 1) {
setTop('#87cefa');
setLeft('#cdcdcd');
} else if (x >= imageSize.quadrantSize && x <= quadrantSize2) {
setRight('#87cefa');
setTop('#cdcdcd');
} else if (x >= quadrantSize2 && x <= quadrantSize3) {
setBottom('#87cefa');
setRight('#cdcdcd');
} else if (x >= quadrantSize3 && x <= quadrantSize4) {
setLeft('#87cefa');
setBottom('#cdcdcd');
}
};
return (
<SafeAreaView style={styles.container}>
<TouchableOpacity
onPress={() => onPress()}
style={{
...
}}
>
<View
style={{
...
}}
/>
</TouchableOpacity>
<Image
ref={imageRef}
style={{
width: imageSize.imageWidth,
height: imageSize.imageHeignt,
justifyContent: 'center',
marginTop: 20,
}}
source={{
uri:
'https://jjj.s3.ap-south-1.amazonaws.com/1/out8.jpeg',
}}
resizeMode="cover"
/>
<Modal
animationType="none"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
console.log('aaa');
}}
>
<View style={{ ...styles.centeredView, borderWidth: 1 }}>
<View style={styles.modalView}>
<ScrollView
scrollToOverflowEnabled={true}
horizontal={true}
ref={scrollViewRef}
>
<Image
style={{
height: imageSize.imageHeignt,
width: 1550,
}}
source={{
uri:
'https://jjj.s3.ap-south-1.amazonaws.com/1/out8.jpeg',
}}
/>
</ScrollView>
</View>
</View>
</Modal>
</SafeAreaView>
);
};
export default App;
我也试图理解这一点: https://upmostly.com/tutorials/settimeout-in-react-components-using-hooks