问题描述
我有一个使用 Animated.timing() 的动画,它在条件 mapIsCentered = true
时将组件滑入查看。当条件不满足时,组件会不优雅地消失。我希望它随着条件的变化而滑入和滑出。
需要注意的一件事是 mapIsCentered
状态在不同的屏幕上更新,并作为道具传递给我正在使用的组件。我已经记录了状态,并在移动地图时更新。
** 幻灯片按预期工作
感谢@Ashwith 的第一个回答
const values = useRef(new Animated.ValueXY({ x: 0,y: 120 })).current;
useEffect(() => {
Animated.timing(values,{
tovalue: mapIsCentered ? { x: 0,y: 0 } : { x: 0,y: 120 },duration: 500,useNativeDriver: false,}).start();
},[mapIsCentered]);
{!walkInProgress && !hasOnGoingWalks && (
<Animated.View
style={{
transform: [{ translateY: values.y }],}}
>
<WeatherToast
translations={translations}
loading={loading}
weather={weather}
/>
</Animated.View>
提前致谢!
解决方法
我已经改变了结构希望它对你有用...
小吃:https://snack.expo.io/@ashwith00/excited-orange
App.js
const walkInProgress = false,hasOnGoingWalks = false;
export default function App() {
const { width } = useWindowDimensions();
const [mapCentered,setMapCentered] = React.useState(false)
const toggle = () => {
setMapCentered((ct) => !ct);
};
return (
<View style={styles.container}>
<WeatherToast mapCentered={mapCentered && !walkInProgress && !hasOnGoingWalks} />
<Button title="shift" onPress={toggle} />
</View>
);
}
WeatherTost.js
export default ({ mapCentered }) => {
const [visible,setVisible] = useState(mapCentered);
const { width } = useWindowDimensions();
const values = React.useRef(new Animated.ValueXY({ x: 0,y: 120 })).current;
React.useEffect(() => {
if (mapCentered) {
setVisible(true);
Animated.timing(values,{
toValue: { x: 0,y: 0 },duration: 300,}).start();
} else {
Animated.timing(values,{
toValue: { x: width,}).start(({ finished }) => {
if (finished) {
setVisible(false);
}
});
}
},[mapCentered]);
const styles = [];
return visible ? (
<Animated.View
style={{
width: 200,height: 200,position: 'absolute',backgroundColor: 'red',transform: [
{
translateX: values.x,},{
translateY: values.y,],}}
/>
) : (
<View />
);
};