[英]Why I can't create a counter within a panHandler in React Native with useState()?
I am stuck here for several hours.我被困在这里几个小时。 Maybe you can help me guys.
也许你们可以帮助我。
I have a react hook and a panHandler inside.我有一个反应钩子和一个 panHandler 里面。 Every time the panHandler is clicked I want to add 1 to the counter.
每次单击 panHandler 时,我都想将 1 添加到计数器。 But it counts only to 1, I can click it 100 times and nothing happens.
但它只计数到 1,我可以单击它 100 次,但没有任何反应。 Can somebody help me with that issue:)?
有人可以帮我解决这个问题:)吗?
It seems as when the setCount is once called, I can not call it a second time.似乎当 setCount 被调用一次时,我不能再次调用它。
Maybe it is too simple or I am missing something.也许它太简单了,或者我错过了一些东西。
import React, { useState, useEffect, useRef } from 'react';
import { Animated, Dimensions, Image, PanResponder, StyleSheet, View, Text } from 'react-native';
export default function Example(props) {
// Initialize the state
const [count, setCount] = useState(0)
// Create the PanResponder Element, usually React.useRef
const _panResponder = React.useRef(
PanResponder.create({
// Ask to be the responder:
onStartShouldSetPanResponder: (evt, gestureState) => true,
onMoveShouldSetPanResponder: (evt, gestureState) => true,
onPanResponderMove: (evt, gestureState) => {
setCount(count + 1)
},
})
).current;
return (
<View>
<View
{..._panResponder.panHandlers}
style={{width: 100, height: 100, backgroundColor: "blue"}}>
</View>
<Text>{count}</Text>
</View>
)
}
if you facing issue then use this library react-native-gesture-handler如果您遇到问题,请使用此库react-native-gesture-handler
its easy to manage state in that.它易于管理 state 。 View documentation here
在此处查看文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.