代码之家  ›  专栏  ›  技术社区  ›  David Geismar

使react本机组件定期闪烁

  •  0
  • David Geismar  · 技术社区  · 6 年前

    我正在尝试使页面上的组件“闪烁”。我在考虑在componentwillmount方法中设置一个visible:true状态,然后在componentdiddupdate中设置超时1s以将状态设置为与前一状态“相反”的状态。如我所见,组件生命周期如下:

    将状态设置为“可见”为“真”(componentwillmount,它只运行一次,不触发重传器) 输入componentDidUpdate

      componentWillMount(){
    
        console.log('in componentWillMount')
        this.setState({visible: true})
      }
      componentDidUpdate(){
        console.log('in componentDidUpdate')
        setTimeout(() =>this.setState({visible: !this.state.visible}), 1000)
      }
    
      // componentWillUnmount(){
      //   clearInterval(this.interval)
      // }
      render(){
        const { textStyle } = styles;
        if (this.state.visible){
          return (
                  <TouchableOpacity onPress={this.props.onPress}>
                    <Pause style={{height: 50, width: 50}}/>
                  </TouchableOpacity>
          );
        }
        else {
          return (
            <View style={{height: 50, width: 50}}>
            </View>
          )
        }
      }
    };
    

    3 回复  |  直到 5 年前
        1
  •  0
  •   Johan    6 年前

    以下是我的作品

    componentDidMount = () => {
      this.interval = setInterval(() => {
        this.setState((state, props) => {
          return {
            visible: !state.visible,
          };
        });
      }, 1000);
    };
    
    componentWillUnmount = () => {
      clearInterval(this.interval);
    };
    

    然后你的渲染可以检查 this.state.visible 以确定是否需要显示。

    或者您可以更改 setState

    this.setState({visible: !this.state.visible})
    
        2
  •  0
  •   EnriqueDev    6 年前

    很可能是因为您使用的是状态和超时。状态是异步设置的,因此,根据您使用的资源数量,更改值可能需要不同的时间。

    为了达到你想要的效果,我建议你使用来自react native的动画框架。检查文档。

        3
  •  0
  •   Yash Ojha    6 年前

    只使用

    setInterval(()=>{//setstate here},time_in_ms)