【发布时间】:2023-03-23 14:00:01
【问题描述】:
我需要用动画将文本从中心向左移动,我不能用 screenWidth/2 和 marginLeft 来做到这一点,因为我需要了解文本长度和其他东西才能把它放在中心。
也许有一种方法可以将 Interpolate 与“justifyContent”或“alignItems”一起使用,任何其他方式都将受到欢迎。
const leftInterpolate = createInterpolate(animatedValue, [0, 1], ['center','flex-start']);
<Animated.Text style={{justifyContent: leftInterpolate}}>
{'blabla'}
</Animated.Text>
更新:
当我尝试第一个答案时出现错误:
问题是我不能将 ref 与 'Animated.View' 一起使用
<Animated.View ref={ref} />
在 RN 0.61.5
0.61.5 及以下版本的解决方案:
import React from 'react';
import { Animated, Easing, Text, View, StyleSheet } from 'react-native';
export default function App() {
const ref = React.useRef(View.prototype);
const animatedValue = React.useRef(new Animated.Value(0)).current;
const [xPos, setXPos] = React.useState(-1);
const startAnimation = () => {
Animated.timing(animatedValue, {
toValue: 1,
duration: 1000,
delay: 1000,
easing: Easing.linear,
useNativeDriver: true,
}).start();
};
React.useEffect(() => {
ref.current?.measure((x, y, w, h, xAbs, yAbs) => {
setXPos(xAbs);
});
startAnimation();
}, [xPos]);
const translateX = animatedValue.interpolate({
inputRange: [0, 1],
outputRange: [0, -xPos],
});
return (
<View style={styles.container}>
<Animated.View style={{ transform: [{ translateX }] }}>
<Text ref={ref}>Some Text</Text>
</Animated.View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
【问题讨论】:
标签: reactjs react-native