简体   繁体   English

如何在 React.js 中的计时器计数 === 0 时设置按钮不可见?

[英]How to set button unvisible when timer count === 0 in React.js?

I am new in React.js and I have a question.我是 React.js 的新手,我有一个问题。

I want to send a feedback by button click.我想通过单击按钮发送反馈。 It is sending via axios request with timeout 3 seconds.它通过axios请求发送,超时 3 秒。

I put Cancel button if user wants to cancel sending feedback for this timeout (3 seconds) - (and axios request is being cancelled as well).如果用户想取消发送此超时(3 秒)的反馈,我会放置“ Cancel按钮(并且axios请求也被取消)。

Then, I put timer on button, but it is situated under text even I use <span> .然后,我将计时器放在按钮上,但即使我使用<span> ,它也位于文本下方。 I attached code to codesandbox .我将代码附加到codeandbox Now it is test mode, just need to fix:现在是测试模式,只需要修复:

  • time above text - it needs to be in left of the text.时间在文本上方 - 它需要在文本的左侧。
  • cancel function is also received wrongly as a props because of console messages (it doesn't cancel parent's state).由于控制台消息(它不会取消父级的状态),取消功能也被错误地作为道具接收。
  • I need Cancel button to be show to 0 count, so I need to unmount button when it is 0 and hide it.我需要Cancel按钮显示为 0 计数,所以我需要在它为 0 时卸载按钮并隐藏它。

Any help will be appreciated.任何帮助将不胜感激。 Thanks!谢谢!

  doIntervalChange = () => {
    if (this.state.count === 0) {
      this.hide();
    }
    this.myInterval = setInterval(() => {
      this.setState(
        prevState => ({
          count: prevState.count - 1
        }),
        () => {
          if (this.state.count === 0) this.hide();
        }
      );
    }, 1000);
  };

doIntervalChange just run 1 time when you place it in comp did mount , try this code :D doIntervalChange 当你把它放在 comp did mount 时只运行 1 次,试试这个代码:D

You have two make two changes here,你有两个在这里做两个改变,

1) In send.js file make changes in following under sendApi() method, 1)send.js文件中的sendApi()方法下进行以下更改,

setTimeout(() => {
  this.setState({
    isLoading: false
  });
  console.log("Ok");
}, 4000);

As the cancel button is populated only when isLoading is true, you can make it to false inside sendApi() method after the setTimeout to remove it after the given time.由于取消按钮仅在isLoading为 true 时isLoading填充,因此您可以在setTimeout之后在sendApi()方法sendApi()其设置为 false 以在给定时间后将其删除。

2) To make the timer count and cancel text to stay in line of the button, 2)为了让计时器计数并取消文本以保持在按钮的行,

Under timer.js change the return statement under render() method like,timer.js更改render()方法下的 return 语句,例如,

return (
  <React.Fragment>{count}</React.Fragment>
);

Forked sandbox分叉沙盒

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM