简体   繁体   English

检查PanResponder值是否超过视图宽度

[英]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.viewWidthcomponentWillMount ,由于被安装在视图之前方法仅呈现。

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 ? 但是也许可以用01作为值来进行不同的处理,所以我在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM