如何平移X、平移Y到某个坐标而不是相对点?
How to translateX, translateY to a certain coordinate rather than a relative point?
我的问题是关于在 react and/or react-native 动画中使用 translateX 和 translateY,将对象动画化到某个点。
这两个变换相对于现有点移动对象。
但是对于场景来说,现有的坐标并不重要,我想确保对象移动到屏幕上可能存在的某个点。
额外的限制是,我无法为样式 top
、bottom
、left
和 right
设置动画,因为在 react-native 中,如果我们为这些样式设置动画,那么我们无法使用导致性能问题的 useNativeDriver={true}
指令。
您可以使用 onLayout
属性在任何 View
组件上获取位置(相对于父级)和 height/width。
像这样的东西应该有用。您可能需要获取更多父 View
组件的位置,具体取决于您当前的结构。
componentDidMount() {
this.animatedValue = new Animated.Value(0);
}
animate() {
const { parentYPosition } = this.state;
Animated.Timing(this.animatedValue, {
toValue: FINAL_POSITION - parentYPosition
}).start();
}
render() {
return (
<View
onLayout={event => {
const { y } = event.nativeEvent.layout;
this.setState({parentYPosition: y})
}}
>
<Animated.View
style={{
position: 'absolute',
top: 0,
transform: [
{
translateY: this.animatedValue
}
/>
/>
);
}
我的问题是关于在 react and/or react-native 动画中使用 translateX 和 translateY,将对象动画化到某个点。
这两个变换相对于现有点移动对象。
但是对于场景来说,现有的坐标并不重要,我想确保对象移动到屏幕上可能存在的某个点。
额外的限制是,我无法为样式 top
、bottom
、left
和 right
设置动画,因为在 react-native 中,如果我们为这些样式设置动画,那么我们无法使用导致性能问题的 useNativeDriver={true}
指令。
您可以使用 onLayout
属性在任何 View
组件上获取位置(相对于父级)和 height/width。
像这样的东西应该有用。您可能需要获取更多父 View
组件的位置,具体取决于您当前的结构。
componentDidMount() {
this.animatedValue = new Animated.Value(0);
}
animate() {
const { parentYPosition } = this.state;
Animated.Timing(this.animatedValue, {
toValue: FINAL_POSITION - parentYPosition
}).start();
}
render() {
return (
<View
onLayout={event => {
const { y } = event.nativeEvent.layout;
this.setState({parentYPosition: y})
}}
>
<Animated.View
style={{
position: 'absolute',
top: 0,
transform: [
{
translateY: this.animatedValue
}
/>
/>
);
}