React native - "this.setState is not a function" пытается оживить цвет фона? - PullRequest
0 голосов
/ 09 июля 2020

Хорошо, я просто пытаюсь изменить oop цвет фона представления, переходя между 3-4 цветами. Я нашел Как анимировать backgroundColor ScrollView в React Native и скопировал дословно, но, глядя на 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>
      );
  }
};

1 Ответ

0 голосов
/ 09 июля 2020

Вы не можете использовать это внутри функционального компонента. Единственная ошибка, которую вы сделали, это то, что вы пытаетесь установить состояние с помощью this.setState внутри функционального компонента вместо использования useState хука, который выполняет ту же работу для функционального компонента.

Просто измените функциональность setState, используя useState и useEffect , как показано ниже: -

//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 хуки, наслаждайтесь!

...