我想在UITableViewCell中实现平移手势。我已经成功地做到了;但是,平移手势会导致每个像素调用shouldUpdateComponent。 (即使我将translateX属性存储为类变量)

class ThreadCell extends React.Component {
    shouldComponentUpdate(nextProps, nextState){
        //Problem: This calls for every pixel moved.
        console.log("shouldComponentUpdate");
        return true;
    }
    translateX = new Animated.Value(0);
    panResponder = PanResponder.create({
        onMoveShouldSetResponderCapture: (e, gs) => { return true; },
        onMoveShouldSetPanResponderCapture: (e, gs) => {  return gs.dx > 0 },
        onPanResponderMove: (e, gestureState) => {
            if(gestureState.dx > 0) {
                this.props.setScrollEnabled(false)
                Animated.event([null, {dx: this.translateX}])(e, gestureState)
            }
        },
        onPanResponderTerminate: (e, gestureState) => {
            console.log("terminate");
            Animated.spring(this.translateX, {
                toValue: 0,
                bounciness: 1
            }).start();
        },
        onPanResponderRelease: (e, {vx, dx}) => {
            console.log("release. DX: ", dx);
            Animated.spring(this.translateX, {
                toValue: 0,
                bounciness: 8,
                speed:48,
            }).start((result) => {
                if(dx > 24){
                    this.props.onMenuSwipe(this.props.sectionTitle, this.props.threadId)
                }else{
                    console.log("nah");
                }
            });
        },
    });
    constructor(props){
        super(props)
    }
    render(){
        return (
            <View>
                <Animated.View
                    style={{transform: [{translateX: this.translateX}]}}  {...this.panResponder.panHandlers}
                >
                <Text>Stuff Here</Text>
                </Animated.View>
            </View>
         )
     }
}

最佳答案

this.props.setScrollEnabled(false)onPanResponderMove中被调用,每当手势移动时就会被调用。

this.props.setScrollEnabled(false)可能在父组件中设置了一个状态,因此它会重新渲染,从而导致所有子组件的shouldComponentUpdate被调用(除非在启用了pure配置的情况下将其连接到Redux)。

您可以将setScrollEnabled移到onStartShouldSetPanResponder,以便仅在手势开始时调用它:

onStartShouldSetPanResponder: (e, gs) => {
  if (gs.dx > 0) {
    this.props.setScrollEnabled(false);
  }
  return true;
},


或者,在父组件中调用setState之前,检查所需的状态更改是否与当前状态不同:

setScrollEnabled(enable) {
  if (this.state.enable !== enable) {
    this.setState({ enable });
  }
}

关于ios - Animated.View + Pan Responder导致对React Native中的每个像素进行重新渲染,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51832676/

10-13 03:52