从 React Native 中的 child 组件更新 parent 状态时找不到变量 (functionName())
Can't find variable (functionName()) when updating parent State from child component in React Native
我正在尝试更新卡片在 parent 组件中的位置以响应 natvive。
我的 parent 组件有这个:
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);
}
在 return 函数中,我传递给 child :
<Screenshot
handleScreenShotPosition={this.handleScreenShotPosition}
position={state.position}
velocityY={this.velocityY}
movingState={this.gestureState}
jarSelected={state.jarSelected}
/>
使用 react-native-gesture-handler 中的 PanGestureHandler child 组件在重新运行函数中看起来像这样:
<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 变量未定义;
我真的不知道为什么 parent child 的状态没有改变。
如何在 child 中声明 handleScreenShotPosition
?如果它是有状态组件,则使用 this.props.handleScreenShotPosition(...)
也尝试使用 ES2015 箭头函数来定义 parent
我正在尝试更新卡片在 parent 组件中的位置以响应 natvive。 我的 parent 组件有这个:
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);
}
在 return 函数中,我传递给 child :
<Screenshot
handleScreenShotPosition={this.handleScreenShotPosition}
position={state.position}
velocityY={this.velocityY}
movingState={this.gestureState}
jarSelected={state.jarSelected}
/>
使用 react-native-gesture-handler 中的 PanGestureHandler child 组件在重新运行函数中看起来像这样:
<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 变量未定义; 我真的不知道为什么 parent child 的状态没有改变。
如何在 child 中声明 handleScreenShotPosition
?如果它是有状态组件,则使用 this.props.handleScreenShotPosition(...)
也尝试使用 ES2015 箭头函数来定义 parent