React native - “this.setState is not a function” trying to animate background color?

后端 未结 1 546
遥遥无期
遥遥无期 2021-01-26 08:50

Alright Im just trying to loop the background color of a view, fading between 3-4 colors. I found How to animate the backgroundColor of a ScrollView in React Native and have cop

相关标签:
1条回答
  • 2021-01-26 09:16

    You can not use this inside a functional component. The only mistake you made is you are trying to set state using this.setState inside a functional component instead of using useState hook which does the same work for functional component.

    Just change your setState functionality using useState and useEffect hook as below:-

    //Set states
    const [backgroundColor, setBackgroundColor] = useState(new Animated.Value(0));
    const [colorValue, setColorValue] = useState(new Animated.Value(0)); 
    
    useEffect(() => {
      setBackgroundColor(new Animated.Value(0));
    }, []);    // this will be only called on initial mounting of component, 
    // so you can change this as your requirement maybe move this in a function which will be called, 
    // you can't directly call setState/useState in render otherwise it will go in a infinite loop.
    useEffect(() => {
      Animated.timing(backgroundColor, {
        toValue: 100,
        duration: 5000
      }).start();
    }, [backgroundColor]);
    
    var color = colorValue.interpolate({
      inputRange: [0, 300],
      outputRange: ['rgba(255, 0, 0, 1)', 'rgba(0, 255, 0, 1)']
    });
    

    This is how it could be done in a class component using useState and useEffect hooks, Enjoy!

    0 讨论(0)
提交回复
热议问题