[英]Check if PanResponder value exceeds View width
I am creating a PanResponder
in my componentWillMount
method 我正在我的
componentWillMount
方法中创建PanResponder
componentWillMount() {
this._panResponder = PanResponder.create({
onMoveShouldSetResponderCapture: () => true,
onMoveShouldSetPanResponderCapture: () => true,
onPanResponderMove: Animated.event([null, { dx: this.state.pan }]),
onPanResponderRelease: (e, {vx, vy}) => {
// here I want to check if pan exceeded the width of the View container
]
});
}
The problem is that I don't know how to detect the size of the width. 问题是我不知道如何检测宽度的大小。
In my render
method, I could do something like this 在我的
render
方法中,我可以做这样的事情
return (
<View onLayout={event => this.setState({ viewWidth: event.nativeEvent.layout.width })}>
..
</View>
);
but I cannot access this.state.viewWidth
in componentWillMount
, since the method is only rendered before the view is mounted. 但我不能访问
this.state.viewWidth
在componentWillMount
,由于被安装在视图之前方法仅呈现。
I am trying to make a slider that goes from left to right, so I need a minimum and maximum X value, where the minimum X value is simply 0. 我试图制作一个从左到右的滑块,所以我需要一个最小和最大X值,其中最小X值就是0。
So when defining the position, I am using 所以在定义位置时,我正在使用
// Current position
const left = pan.interpolate({
inputRange: [0, viewWidth],
outputRange: [0, viewWidth],
extrapolate: 'clamp'
});
return (
<View style={styles.container}>
<View style={{ position: 'absolute', left, width: 100, height: 100 , backgroundColor: 'red' }} />
</View>
);
but maybe it could be done differently with 0
and 1
as values, so I in onPanResponderRelease
could simply check if the pan
value exceeds 1
? 但是也许可以用
0
和1
作为值来进行不同的处理,所以我在onPanResponderRelease
可以简单地检查pan
值是否超过1
?
I would initialize the viewWidth
state to false
, and use componentDidUpdate
to initialize the PanResponder
. 我会将
viewWidth
状态初始化为false
,并使用componentDidUpdate
初始化PanResponder
。 Just check that state.viewWidth
is set and that it wasn't in prevState.viewWidth
: 只需检查是否设置了
state.viewWidth
,并且它不在prevState.viewWidth
:
componentDidUpdate(prevProps, prevState) {
if (this.state.viewWidth && prevState.viewWidth === false) {
this._panResponder = PanResponder.create({
onMoveShouldSetResponderCapture: () => true,
onMoveShouldSetPanResponderCapture: () => true,
onPanResponderMove: Animated.event([null, { dx: this.state.pan }]),
onPanResponderRelease: (e, {vx, vy}) => {
// here I want to check if pan exceeded the width of the View container
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.