首页 > 解决方案 > React native - “this.setState 不是函数”试图为背景颜色设置动画?

问题描述

好吧,我只是想循环视图的背景颜色,在 3-4 种颜色之间褪色。我找到了如何在 React Native 中为 ScrollView 的 backgroundColor 设置动画并逐字复制,但是看着 Snack,我相信这个答案已经过时了。

使用以下内容,我收到错误:

this.setState 不是函数

export default props => {
  let [fontsLoaded] = useFonts({
    'Inter-SemiBoldItalic': 'https://rsms.me/inter/font-files/Inter-SemiBoldItalic.otf?v=3.12',
        'SequelSans-RomanDisp' : require('./assets/fonts/SequelSans-RomanDisp.ttf'),
        'SequelSans-BoldDisp' : require('./assets/fonts/SequelSans-BoldDisp.ttf'),
        'SequelSans-BlackDisp' : require('./assets/fonts/SequelSans-BlackDisp.ttf'),
  });
  if (!fontsLoaded) {
    return <AppLoading />;
  } else {

      //Set states
      this.state = {
        backgroundColor: new Animated.Value(0)
      };
      this.setState({ backgroundColor: new Animated.Value(0) }, () => {
       Animated.timing(this.state.backgroundColor, {
        toValue: 100,
        duration: 5000
      }).start();
    });

        var color = this.state.colorValue.interpolate({
            inputRange: [0, 300],
            outputRange: ['rgba(255, 0, 0, 1)', 'rgba(0, 255, 0, 1)']
        });

    const styles = StyleSheet.create({
      container: { flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
      backgroundColor: this.state.backgroundColor.interpolate({
                inputRange: [0, 100],
                outputRange: ["#00aaFF", "#808080"]
              })
    },

然后我在这里引用这种风格:

return (
        <Animated.View style={styles.container}>
          <View style={styles.textWrapper}>
            <Text style={styles.myText}>Login</Text>
          </View>
        </Animated.View>
      );

我在这里做错了什么?

更新: - 渲染的钩子比上一次渲染时更多

    export default props => {
  let [fontsLoaded] = useFonts({
    'Inter-SemiBoldItalic': 'https://rsms.me/inter/font-files/Inter-SemiBoldItalic.otf?v=3.12',
        'SequelSans-RomanDisp' : require('./assets/fonts/SequelSans-RomanDisp.ttf'),
        'SequelSans-BoldDisp' : require('./assets/fonts/SequelSans-BoldDisp.ttf'),
        'SequelSans-BlackDisp' : require('./assets/fonts/SequelSans-BlackDisp.ttf'),
  });
  if (!fontsLoaded) {
    return <AppLoading />;
  } else {

    //Set states
      const [backgroundColor, setBackgroundColor] = 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(this.state.backgroundColor, {
          toValue: 100,
          duration: 5000
        }).start();
      }, [backgroundColor]);

      var color = this.state.colorValue.interpolate({
        inputRange: [0, 300],
        outputRange: ['rgba(255, 0, 0, 1)', 'rgba(0, 255, 0, 1)']
      });

    const styles = StyleSheet.create({
      container: { flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
      backgroundColor: color
    },
      textWrapper: {
        height: hp('70%'), // 70% of height device screen
        width: wp('80%'),   // 80% of width device screen
        backgroundColor: '#fff',
        justifyContent: 'center',
        alignItems: 'center',
      },
      myText: {
        fontSize: hp('2%'), // End result looks like the provided UI mockup
        fontFamily: 'SequelSans-BoldDisp'
      }
    });

      return (
        <Animated.View style={styles.container}>
          <View style={styles.textWrapper}>
            <Text style={styles.myText}>Login</Text>
          </View>
        </Animated.View>
      );
  }
};

标签: javascriptreactjsreact-nativeanimation

解决方案


您不能在功能组件中使用它。您犯的唯一错误是您尝试在功能组件中使用 this.setState 设置状态,不是使用对功能组件执行相同工作的 useState 挂钩

只需使用useStateuseEffect挂钩更改您的 setState 功能,如下所示:-

//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)']
});

这就是使用useState 和 useEffect钩子在类组件中完成的方式,享受吧!


推荐阅读