【发布时间】:2020-06-02 10:37:34
【问题描述】:
我想用平移响应器监听我正在移动的视图的位置。我正在使用 onLayout 道具来获取宽度、高度、x 和 y 位置,但它只在第一次渲染时运行。有什么想法吗?
代码如下:
import React, { useState, useRef } from "react";
import {
View,
Animated,
PanResponder,
Dimensions,
StyleSheet,
} from "react-native";
const WINDOW_HEIGHT = Dimensions.get("window").height;
export default function Cropper({ photo }) {
const [height, setHeight] = useState(WINDOW_HEIGHT / 2); // Use in future
const pan = useRef(new Animated.ValueXY()).current;
const panResponder = useRef(
PanResponder.create({
onStartShouldSetPanResponder: () => true,
onPanResponderMove: Animated.event([null, { dy: pan.y }]),
onPanResponderRelease: () => {
pan.flattenOffset();
},
})
).current;
const onLayout = (event) => {
const {
nativeEvent: { layout },
} = event;
// Recalculate top and buttom views' height (setNativeProps)
};
const panStyle = {
transform: pan.getTranslateTransform(),
};
return (
<View style={styles.container}>
<View style={styles.blurView} />
<Animated.View
onLayout={(event) => onLayout(event)}
{...panResponder.panHandlers}
style={[
styles.cropper,
panStyle,
{
height: height,
},
]}
/>
<View style={styles.blurView} />
<View style={styles.bottomButtonsContainer}></View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
blurView: {
flex: 1,
width: "100%",
backgroundColor: "rgba(0, 0, 0, .9)",
},
cropper: {
width: "100%",
backgroundColor: "red",
},
bottomButtonsContainer: {
position: "absolute",
bottom: 0,
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
width: "100%",
height: 120,
},
});
我要做的是在用户移动它时获取中间视图位置,然后重新计算顶部和底部视图的高度。
【问题讨论】:
标签: javascript css reactjs react-native