动画和getDerivedStateFromProps

时间:2018-06-01 10:43:15

标签: reactjs react-native

弃用componentWillReceiveProps并且替换getDerivedStateFromProps返回最终状态,我将如何随着时间的推移逐渐改变状态(即动画内容){{1 }}?

使用getDerivedStateFromProps,以下工作正常:

componentWillReceiveProps

我如何使用state = { itemOpacity: new Animated.Value(0.25) }; componentWillReceiveProps(nextProps) { if (this.props.items.visible !== nextProps.items.visible) { let value = 0; if (nextProps.items.visible) { value = 1; } Animated.timing(this.state.itemOpacity, { toValue: value, duration: 200, }).start(); } } 执行此类操作?或者我的动画模式是愚蠢的?

2 个答案:

答案 0 :(得分:1)

使用newProps和previousState参数调用getDerivedStateFromProps。所以你可以使用previousState作为动画:

static getDerivedStateFromProps(nextProps, prevState) {

  let value = 0;
  if (nextProps.items.visible) {
    value = 1;
  }

  Animated.timing(prevState.itemOpacity, {
    toValue: value,
    duration: 200,
  }).start();

  return {
    // update state
  }
}

答案 1 :(得分:1)

简单的答案就是不要使用状态来制作动画(感谢dentemm的帮助):

itemOpacity = new Animated.Value(0.25);

class TestScreen extends Component {

  getDerivedStateFromProps(nextProps) {
      let value = 0;

      if (nextProps.items.visible) {
        value = 1;
      }

      Animated.timing(itemOpacity, {
        toValue: value,
        duration: 200,
      }).start();

    return null;
  }
}