草庐IT

javascript - 为数组中的每个项目创建独立的秒表。根据API返回的数据设置停止时间

coder 2024-07-23 原文

创建独立的秒表。我有两个名为 AB 的元素。当我点击 A 元素时,它的描述 Hello 和秒表将出现。当我点击 B 元素时,它的 World 描述和秒表就会出现。我的秒表有问题。当我单击元素 A 并启动秒表时,转到元素 B 然后此秒表正在运行。我的目标是,当我为元素 A 运行秒表时,它将只计算这个元素。当他在元素 A 中停止秒表,然后转到元素 B 时,在该元素中,秒表将仅针对该元素计数。我在 B 元素中停止秒表并转到 A 元素,我将能够恢复秒表。我要求一些想法来解决这个问题。 我通过调用 startTime 函数发送(方法 post -> 带有开始日期的对象)。我单击停止 -> 调用 stopTimer(方法发布 -> 我发送带有结束日期的对象)。作为响应,该项目被压印有开始日期和结束日期,并且秒数(结束日期和开始日期之间的差异)被保存在状态中。根据这些数据(开始日期、结束日期和秒),设置秒表停止的时间。如何关闭我的浏览器以下载此数据以设置它停止的时间。 请给我一些提示。我会定期更正我的代码并将其插入此处。

预期效果:

点击元素 A -> 开始秒表 -> 秒表停止 -> 点击元素 B -> 开始秒表 -> 返回元素 A -> 在定时器停止时恢复定时器

完整代码在这里:https://stackblitz.com/edit/react-x9h42z

部分代码:

App.js

class App extends React.Component {
  constructor() {
    super();

    this.state = {

      items: [
        {
          name: 'A',
          description: 'Hello'
        },
        {
          name: 'B',
          description: 'World'
        }
      ],
      selectIndex: null
    };
  }

  select = (index) => {
    this.setState({
      selectIndex: index
    })
  }


  render() {
    console.log(this.state.selectIndex)
    return (
      <div>
        <ul>
          {
            this.state.items
              .map((item, index) =>
                <Item
                  key={index}
                  index={index}
                  item={item}
                  select={this.select}
                  items = {this.state.items}
                  selectIndex = {this.state.selectIndex}
                />
              )
          }
        </ul>
         <ItemDetails
            items = {this.state.items}
            selectIndex = {this.state.selectIndex}

        />
      </div>
    );
  }
}

秒表

class Stopwatch extends Component {
  constructor() {
    super();

    this.state = {
      timerOn: false,
      timerStart: 0,
      timerTime: 0
    };
  }

  startTimer = () => {
    this.setState({
      timerOn: true,
      timerTime: this.state.timerTime,
      timerStart: Date.now() - this.state.timerTime
    });
    this.timer = setInterval(() => {
      this.setState({
        timerTime: Date.now() - this.state.timerStart
      });
    }, 10);
  };

  stopTimer = () => {
    this.setState({ timerOn: false });
    clearInterval(this.timer);
  };

  resetTimer = () => {
    this.setState({
      timerStart: 0,
      timerTime: 0
    });
  };

  render() {
      const { timerTime } = this.state;
      let centiseconds = ("0" + (Math.floor(timerTime / 10) % 100)).slice(-2);
      let seconds = ("0" + (Math.floor(timerTime / 1000) % 60)).slice(-2);
      let minutes = ("0" + (Math.floor(timerTime / 60000) % 60)).slice(-2);
      let hours = ("0" + Math.floor(timerTime / 3600000)).slice(-2);

    return (
      <div>


    <div className="Stopwatch-display">
      {hours} : {minutes} : {seconds} : {centiseconds}
    </div>


    {this.state.timerOn === false && this.state.timerTime === 0 && (
    <button onClick={this.startTimer}>Start</button>
    )}

    {this.state.timerOn === true && (
      <button onClick={this.stopTimer}>Stop</button>
    )}

    {this.state.timerOn === false && this.state.timerTime > 0 && (
      <button onClick={this.startTimer}>Resume</button>
    )}

    {this.state.timerOn === false && this.state.timerTime > 0 && (
      <button onClick={this.resetTimer}>Reset</button>
    )}
        </div>
      );
    }
}

最佳答案

您需要为每个列表项创建两个秒表实例。我已经更改了链接 link你提供。 我在你的列表数组中为每个对象添加了秒表,每个对象都有一个唯一的键,让 React 知道它们是不同的组件。 现在,我只是简单地用秒表渲染所有列表项,并在切换后保持每个秒表的状态,我只是使用简单的 display none 技术,而不是完全删除组件。 检查代码,让我知道它是否适合您?

import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';


class Item extends Component {

  render() {
    const selectItem = this.props.items[this.props.selectIndex]
    console.log(selectItem);
    
    return ( 
      
        <li onClick={() => this.props.select(this.props.index)}>
          <div>
            Name:{this.props.item.name}
          </div>
        </li>
    )
  }
}

class ItemDetails extends Component {
 
  render() {
    const selectItem = this.props.items[this.props.selectIndex]
    console.log(selectItem);
    let content = this.props.items.map((item, index) => {
      return (
        <div className={this.props.selectIndex === index?'show':'hide'}>
          <p>
              Description:{item.description}
          </p>
          {item.stopWatch}
        </div>
      );
    })
    return (  
      <div>
        {selectItem ?
            content
          :
          null
        }
      </div>
    )
  }
}

class App extends React.Component {
  constructor() {
    super();

    this.state = {

      items: [
        {
          name: 'A',
          description: 'Hello',
          stopWatch: <Stopwatch key={1} />
        },
        {
          name: 'B',
          description: 'World',
          stopWatch: <Stopwatch key={2} />
        }
      ],
      selectIndex: null
    };
  }

  select = (index) => {
    this.setState({
      selectIndex: index
    })
  }


  render() {
    console.log(this.state.selectIndex)
    return (
      <div>
        <ul>
          {
            this.state.items
              .map((item, index) =>
                <Item
                  key={index}
                  index={index}
                  item={item}
                  select={this.select}
                  items = {this.state.items}
                  selectIndex = {this.state.selectIndex}
                />
              )
          }
        </ul>
         <ItemDetails
            items = {this.state.items}
            selectIndex = {this.state.selectIndex}

        />
      </div>
    );
  }
}


class Stopwatch extends Component {
  constructor() {
    super();

    this.state = {
      timerOn: false,
      timerStart: 0,
      timerTime: 0
    };
  }

  startTimer = () => {
    this.setState({
      timerOn: true,
      timerTime: this.state.timerTime,
      timerStart: Date.now() - this.state.timerTime
    });
    this.timer = setInterval(() => {
      this.setState({
        timerTime: Date.now() - this.state.timerStart
      });
    }, 10);
  };

  stopTimer = () => {
    this.setState({ timerOn: false });
    clearInterval(this.timer);
  };

  resetTimer = () => {
    this.setState({
      timerStart: 0,
      timerTime: 0
    });
  };

  render() {
      const { timerTime } = this.state;
      let centiseconds = ("0" + (Math.floor(timerTime / 10) % 100)).slice(-2);
      let seconds = ("0" + (Math.floor(timerTime / 1000) % 60)).slice(-2);
      let minutes = ("0" + (Math.floor(timerTime / 60000) % 60)).slice(-2);
      let hours = ("0" + Math.floor(timerTime / 3600000)).slice(-2);

    return (
      <div>
      

    <div className="Stopwatch-display">
      {hours} : {minutes} : {seconds} : {centiseconds}
    </div>


    {this.state.timerOn === false && this.state.timerTime === 0 && (
    <button onClick={this.startTimer}>Start</button>
    )}

    {this.state.timerOn === true && (
      <button onClick={this.stopTimer}>Stop</button>
    )}

    {this.state.timerOn === false && this.state.timerTime > 0 && (
      <button onClick={this.startTimer}>Resume</button>
    )}
    
    {this.state.timerOn === false && this.state.timerTime > 0 && (
      <button onClick={this.resetTimer}>Reset</button>
    )}
        </div>
      );
    }
}


render(<App />, document.getElementById('root'));
h1, p {
  font-family: Lato;
}

.show {
  display: block;
}

.hide {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

关于javascript - 为数组中的每个项目创建独立的秒表。根据API返回的数据设置停止时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56960599/

有关javascript - 为数组中的每个项目创建独立的秒表。根据API返回的数据设置停止时间的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  4. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  5. ruby-on-rails - Ruby net/ldap 模块中的内存泄漏 - 2

    作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代

  6. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  7. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  8. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  9. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  10. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

随机推荐