为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

开心每一天1111 2022-11-11 16:09:50
好的,我尝试每 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)我怎样才能做到这一点?
查看完整描述

1 回答

?
慕仙森

TA贡献1827条经验 获得超7个赞

您的组件被编写为功能组件,而不是类。要创建有状态的功能组件,您需要使用 hook setState。您收到此错误是因为setState组件上没有对象属性或this. 您还需要使用useEffect挂钩来设置间隔。


https://reactjs.org/docs/hooks-reference.html


import React, { useState } from 'react';


export default props => {

  let [fontsLoaded] = useFonts({

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

  });


  const color = "#fff";

  const colorAnimTime = 36000;

  const [time, setTime] = useState(0);


  useEffect(() => {

    const interval = setInterval(() => {

      setTime(new Date().getMilliseconds));

    }, 1000);

    return () => clearInterval(interval);

  }, []);



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

 


查看完整回答
反对 回复 2022-11-11
  • 1 回答
  • 0 关注
  • 101 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信