react-native - 从 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 变量未定义;我真的不知道为什么父子的状态没有改变。
解决方案
handleScreenShotPosition
在孩子身上是如何声明的?如果它是一个有状态的组件,那么使用this.props.handleScreenShotPosition(...)
也尝试使用 ES2015 箭头函数来定义父组件
推荐阅读
- c# - EF Core 3.1.1 避免异常“数据类型 text 和 varchar 在等于运算符中不兼容”,就像 LINQPad 6 一样
- git - 如何撤消将分支同步到主线?
- html - Laravel Barryvdh\DomPDF 内联块两个不同高度的 div
- github - 在 Github 提交消息中参考 Monday.com 项目 ID
- c++ - 用 std::vector 替换命令行参数 int argc 和 char** argv
- java - Citrus 框架 - 无法成功构建示例
- javascript - 使用 google api 显示城市中的类别地点
- angular - Angular 8,从另一个组件调用函数时遇到问题
- swift - SwiftUI:从其他组件提供for循环上限
- xamarin - 我们可以使用 Tap Gesture Recognizer 为普通视图(例如标签)添加视觉状态吗?