【问题标题】:Animation duration issue动画时长问题
【发布时间】:2019-11-25 20:48:02
【问题描述】:

我尝试为视图设置动画以隐藏和显示它。持续时间可以打开它(500),但是当我关闭它时它不起作用,持续时间不受尊重(它直接关闭)。

这是我的代码:

const {height, width} = Dimensions.get('window');

  const [initialHeight] = useState(new Animated.Value(0));

  useEffect(() => {
    if (state === true) {
      Animated.timing(initialHeight, {
        toValue: height - 400,
        duration: 500,
      }).start();
    } else {
      Animated.timing(initialHeight, {
        toValue: 0,
        duration: 500,
      }).start();
    }
  }, [height, initialHeight, state]);

...

<Animated.View style={{height: initialHeight, paddingVertical: 12}}>

我错过了什么?

---编辑

我做了这个更改,但并没有解决问题:

const [initialHeight, setInitialHeight] = useState(new Animated.Value(0));

  useEffect(() => {
    if (state === true) {
      Animated.timing(initialHeight, {
        toValue: height - 400,
        duration: 500,
      }).start(() => {
        setInitialHeight(new Animated.Value(height - 400));
      });
    } else {
      Animated.timing(initialHeight, {
        toValue: 0,
        duration: 500,
      }).start(() => {
        setInitialHeight(new Animated.Value(0));
      });
    }
  }, [height, initialHeight, state]);

【问题讨论】:

  • state 变量是什么?
  • 这是一个布尔值。它是从包含组件传递的道具。为真时,动画起作用,为假时,就像视图没有动画一样,直接隐藏。

标签: reactjs react-native react-hooks react-animated


【解决方案1】:

您可以使用 useRef 来存储您的动画值:

const initialHeight = useRef(new Animated.Value(0)).current;

而且您不必手动更新它:

useEffect(() => {
    if (state) { //If state is a boolean, you don't need to do === true
      Animated.timing(initialHeight, {
        toValue: height - 400,
        duration: 500,
      }).start();
    } else {
      Animated.timing(initialHeight, {
        toValue: 0,
        duration: 500,
      }).start();
    }
  }, [state]); // If you want to initiate your animation only on this prop change

别忘了检查height - 400 的结果。每个动画,从height - 4000 并反向需要500ms。

【讨论】:

    【解决方案2】:

    好吧,我终于找到了问题所在,并找到了解决方案。每次道具状态发生变化时,组件都会完全重新渲染。所以我将父组件中的状态变量更改为这样的对象:{firstRender:true,opened:false}并根据这些参数更改初始高度的值。它就像一个魅力! 我确定有更好的解决方案,但搜索了几个小时后我找不到任何解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多