首页 > 解决方案 > 从 React Native 中的子组件更新父状态时找不到变量 (functionName())

问题描述

我正在尝试在 react natvive 中更新父组件中卡片的位置。我的父组件有这个:

class JarList extends React.Component {
  state = {
    position: { width: cardWidth, height: cardHeight, x: initialCardX, y: initialCardY },
    jarSelected: false,
  };


updateScreenshotPosition(position) {
    springTransition();
    this.setState({ position, jarSelected: true });
  }

  handleScreenShotPosition(position) {
    updateScreenshotPosition(position);
  }

在返回函数中,我传递给孩子:

  <Screenshot
          handleScreenShotPosition={this.handleScreenShotPosition}
          position={state.position}
          velocityY={this.velocityY}
          movingState={this.gestureState}
          jarSelected={state.jarSelected}
        />

使用 react-native-gesture-handler 中的 PanGestureHandler,子组件在 rerun 函数中如下所示:

 <PanGestureHandler
          onGestureEvent={e => {
            let newPosition = {
              width: position.width,
              height: position.height,
              x: position.x + e.nativeEvent.translationX,
              y: position.y + e.nativeEvent.translationY,
            };
            handleScreenShotPosition(newPosition);
          }}
        >
          <Animated.View
            style={{
              position: 'absolute',
              width: jarSelected ? width : this.animatedWidth,
              height: jarSelected ? height : this.animatedHeight,
              backgroundColor: 'red',
              left: jarSelected ? x : this.animatedX,
              top: y,
            }}
          ></Animated.View>
        </PanGestureHandler>

所以我遇到的问题是应用程序崩溃说 updateScreenshotPosition 变量未定义;我真的不知道为什么父子的状态没有改变。

标签: react-nativereact-native-reanimatedreact-native-gesture-handler

解决方案


handleScreenShotPosition在孩子身上是如何声明的?如果它是一个有状态的组件,那么使用this.props.handleScreenShotPosition(...)也尝试使用 ES2015 箭头函数来定义父组件


推荐阅读