使react-native组件以固定的时间间隔闪烁

问题描述 投票:0回答:3

我试图让我的页面上的组件“闪烁”。我在考虑在componentWillMount方法中设置visible:true状态,​​然后在componentDidUpdate中设置1s超时,将状态设置为前一状态的“反向”。正如我所看到的,组件生命周期如下所示:

将state设置为true(仅运行一次并且不触发重新渲染的componentWillMount)进入componentdidUpdate等待1s隐藏组件(setstate为visible false)进入componentDidUpdate等待1s显示组件(setstate为visible true)

然而,我的组件闪烁,但隐藏和显示的间隔不规则,它们改变,似乎不遵循1s逻辑

这是我的组件代码:

class ResumeChronoButton扩展Component {

  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>
      )
    }
  }
};

如何使组件以固定的时间间隔闪烁。

react-native animation state
3个回答
0
投票

以下适用于我

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})

0
投票

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

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


0
投票

只是用

setInterval(()=>{//setstate here},time_in_ms)
© www.soinside.com 2019 - 2024. All rights reserved.