我需要用动画将文本从中间移动到左边,我不能用screenWidth/2和marginLeft这样做,因为这样我需要了解文本长度和其他东西来把它放在中间。
也许有一种方法可以使用插值与'justifyContent'或'alignItems',任何其他方式将是受欢迎的。
const leftInterpolate = createInterpolate(animatedValue, [0, 1], ['center','flex-start']);
<Animated.Text style={{justifyContent: leftInterpolate}}>
{'blabla'}
</Animated.Text>
更新:
当我尝试第一个答案时,我得到了一个错误:
问题是,我不能使用ref与'动画。视图'
<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',
},
});
1条答案
按热度按时间7ajki6be1#
您可以测量文本的绝对
X
位置并相应地进行翻译。试试demo。