Storing non-state variables in functional components

后端 未结 4 1126
梦谈多话
梦谈多话 2020-12-25 10:45

Below are two React Components that do almost the same thing. One is a function; the other is a class. Each Component has an Animated.Value with an asy

4条回答
  •  情歌与酒
    2020-12-25 11:23

    The useRef hook is not just for DOM refs, but can store any mutable value you like.

    Example

    function FunctionalBar(props) {
      const [foo] = useState(new Animated.Value(0));
      const _foo = useRef(0);
    
      function showFoo() {
        let anim = Animated.timing(foo, { toValue: 1, duration: 1000, useNativeDriver: true });
        anim.start(() => console.log(_foo.current));
      }
    
      useEffect(() => {
        function _onChangeFoo({ value }) {
          _foo.current = value;
        }
    
        foo.addListener(_onChangeFoo);
        showFoo();
        return () => foo.removeListener(_onChangeFoo);
      }, []);
    
      return ;
    }
    

提交回复
热议问题