React Native - 如何每 x 毫秒重新渲染一个组件?

好的,我尝试每 x 毫秒更新一次组件的属性和/或文本。我深入研究了https://www.npmjs.com/package/react-interval-renderer等,但是我遇到了与 s 相关的错误。


我现在看的是简单地反应原生(IOS)。如何更新生效日期(毫秒)但是在将其格式化为我的文件时遇到问题。


我有:


export default props => {

  let [fontsLoaded] = useFonts({

    'Inter-SemiBoldItalic': 'https://rsms.me/inter/font-files/Inter-SemiBoldItalic.otf?v=3.12',

  });


  this.state ={

   color: "#fff",

   colorAnimTime: 36000,

   time: 0

  }


    setInterval(() => {

      this.setState({

        time: new Date().getMilliseconds()

      });

    }, 1000);



//------------------------------------------------------------------->

  if (!fontsLoaded) {

    return <AppLoading />;

  } else {


    const styles = StyleSheet.create({

      container: { flex: 1,

      alignItems: 'center',

      justifyContent: 'center',

    },

      textWrapper: {

        height: hp('70%'), // 70% of height device screen

        width: wp('80%'),   // 80% of width device screen

        justifyContent: 'center',

        alignItems: 'center',

      },

      myText: {

        fontSize: hp('5.5%'), // End result looks like the provided UI mockup

        fontFamily: 'SequelSans-BlackDisp'

      }

    });


      return (

        <AnimatedBackgroundColorView

        color='#00acdd'

        delay={0.5}

        duration={36000}

        initialColor={this.state.color}

        style={styles.container}>

          <View style={styles.textWrapper}>

            <Text style={styles.myText}>COLOR</Text>

          </View>

        </AnimatedBackgroundColorView>

      );

  }

引用的答案用于componentDidMount() {括起来setInterval,但是如果我把它放在我目前拥有setInterval


现在我得到


this.setState 不是函数


并尝试将其绑定setInterval到右侧this,但我相信我不明白如何设置我的文件。


1000 毫秒后,我想更改我的“颜色”<AnimatedBackgroundColorView>并重新加载组件。(所以它再次动画 - https://www.npmjs.com/package/react-native-animated-background-color-view)


我怎样才能做到这一点?


开心每一天1111
浏览 105回答 1
1回答

慕仙森

您的组件被编写为功能组件,而不是类。要创建有状态的功能组件,您需要使用 hook setState。您收到此错误是因为setState组件上没有对象属性或this. 您还需要使用useEffect挂钩来设置间隔。https://reactjs.org/docs/hooks-reference.htmlimport React, { useState } from 'react';export default props => {&nbsp; let [fontsLoaded] = useFonts({&nbsp; &nbsp; 'Inter-SemiBoldItalic': 'https://rsms.me/inter/font-files/Inter-SemiBoldItalic.otf?v=3.12',&nbsp; });&nbsp; const color = "#fff";&nbsp; const colorAnimTime = 36000;&nbsp; const [time, setTime] = useState(0);&nbsp; useEffect(() => {&nbsp; &nbsp; const interval = setInterval(() => {&nbsp; &nbsp; &nbsp; setTime(new Date().getMilliseconds));&nbsp; &nbsp; }, 1000);&nbsp; &nbsp; return () => clearInterval(interval);&nbsp; }, []);//------------------------------------------------------------------->&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript