簡體   English   中英

我在 reactjs 有一個秒表,如何將每個數字添加到某種數組中以顯示每個數字?

[英]I have a stopwatch in reactjs, how can I add each number into some sort of array to show each number?

我使用反應創建了一個秒表。 我的秒表從 0 開始,並在按下帶有 componenDidMount 和 componentWillMount 的空格按鈕時停止。 我的問題是,我似乎無法弄清楚如何使用秒表返回的數字創建某種列表。 我創建了:

  times = () => {
    this.setState(previousState => ({
      myArray: [...previousState.myArray, this.state.milliSecondsElapsed]
    }));

  };

然后在 render() 中打印它。

<h1>{this.times}</h1>

我想要做的是創建某種數組來跟蹤我的 handleStart 和 handleStop 方法中的 milliSecondsElapsed。

這就是我所擁有的。

import React, {Component} from "react";
import Layout from '../components/MyLayout.js';

export default class Timer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      milliSecondsElapsed: 0,
      timerInProgress: false // state to detect whether timer has started
    };
    this.updateState = this.updateState.bind(this);
    this.textInput = React.createRef();
  }

  componentDidMount() {
    window.addEventListener("keypress", this.keyPress);
  }

  componentWillUnmount() {
    window.removeEventListener("keypress", this.keyPress);
  }

  textInput = () => {
    clearInterval(this.timer);
  };
  updateState(e) {
    this.setState({})
    this.setState({ milliSecondsElapsed: e.target.milliSecondsElapsed });
  }

  keyPress = (e) => {
    if (e.keyCode === 32) {
      // some logic to assess stop/start of timer
      if (this.state.milliSecondsElapsed === 0) {
        this.startBtn.click();
      } else if (this.state.timerInProgress === false) {
        this.startBtn.click();
      } else {
        this.stopBtn.click();
      }
    }
  };

  handleStart = () => {
    if (this.state.timerInProgress === true) return;

    this.setState({
      milliSecondsElapsed: 0
    });
    this.timer = setInterval(() => {
      this.setState(
        {
          milliSecondsElapsed: this.state.milliSecondsElapsed + 1,
          timerInProgress: true
        },
        () => {
          this.stopBtn.focus();
        }
      );
    }, 10);
  };
  handleStop = () => {
    this.setState(
      {
        timerInProgress: false
      },
      () => {
        clearInterval(this.timer);
        this.startBtn.focus();
      }
    );
  };

  times = () => {
    this.setState(previousState => ({
      myArray: [...previousState.myArray, this.state.milliSecondsElapsed]
    }));

  };

  render() {
    return (
        <Layout>
          <div className="index" align='center'>
            <input 
              value={this.state.milliSecondsElapsed/100}
              onChange={this.updateState}
              ref={this.textInput}
              readOnly={true}
            />
            <button onClick={this.handleStart} ref={(ref) => (this.startBtn = ref)}>
              START
            </button>
            <button onClick={this.handleStop} ref={(ref) => (this.stopBtn = ref)}>
              STOP
            </button>
            <h1>{this.state.milliSecondsElapsed/100}</h1>
          </div>

        
      </Layout>
    


    );
  }
}

問題

this.times是一個僅更新 state 的 function,它不返回任何可渲染的 JSX。

times = () => {
  this.setState((previousState) => ({
    myArray: [...previousState.myArray, this.state.milliSecondsElapsed]
  }));
};

解決方案

  1. 創建一個myArray state。

     this.state = { myArray: [], // <-- add initial empty array milliSecondsElapsed: 0, timerInProgress: false // state to detect whether timer has started };
  2. 將 state 更新邏輯從this.times移動到this.handleStop

     handleStop = () => { this.setState( (previousState) => ({ timerInProgress: false, myArray: [...previousState.myArray, // <-- shallow copy existing data this.state.milliSecondsElapsed / 100 // <-- add new time ] }), () => { clearInterval(this.timer); this.startBtn.focus(); } ); };
  3. 將經過時間的數組呈現為逗號分隔的列表。

     <div>{this.state.myArray.join(", ")}</div>

完整代碼

class Timer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      myArray: [],
      milliSecondsElapsed: 0,
      timerInProgress: false // state to detect whether timer has started
    };
    this.updateState = this.updateState.bind(this);
    this.textInput = React.createRef();
  }

  componentDidMount() {
    window.addEventListener("keypress", this.keyPress);
  }

  componentWillUnmount() {
    window.removeEventListener("keypress", this.keyPress);
  }

  textInput = () => {
    clearInterval(this.timer);
  };

  updateState(e) {
    this.setState({ milliSecondsElapsed: e.target.milliSecondsElapsed });
  }

  keyPress = (e) => {
    if (e.keyCode === 32) {
      // some logic to assess stop/start of timer
      if (this.state.milliSecondsElapsed === 0) {
        this.startBtn.click();
      } else if (this.state.timerInProgress === false) {
        this.startBtn.click();
      } else {
        this.stopBtn.click();
      }
    }
  };

  handleStart = () => {
    if (this.state.timerInProgress === true) return;

    this.setState({
      milliSecondsElapsed: 0
    });
    this.timer = setInterval(() => {
      this.setState(
        {
          milliSecondsElapsed: this.state.milliSecondsElapsed + 1,
          timerInProgress: true
        },
        () => {
          this.stopBtn.focus();
        }
      );
    }, 10);
  };

  handleStop = () => {
    this.setState(
      (previousState) => ({
        timerInProgress: false,
        myArray: [
          ...previousState.myArray,
          this.state.milliSecondsElapsed / 100
        ]
      }),
      () => {
        clearInterval(this.timer);
        this.startBtn.focus();
      }
    );
  };

  render() {
    return (
      <div>
        <div className="index" align="center">
          <input
            value={this.state.milliSecondsElapsed / 100}
            onChange={this.updateState}
            ref={this.textInput}
            readOnly={true}
          />
          <button
            onClick={this.handleStart}
            ref={(ref) => (this.startBtn = ref)}
          >
            START
          </button>
          <button onClick={this.handleStop} ref={(ref) => (this.stopBtn = ref)}>
            STOP
          </button>
          <h1>{this.state.milliSecondsElapsed / 100}</h1>
        </div>
        <div>{this.state.myArray.join(", ")}</div>
      </div>
    );
  }
}

編輯 i-have-a-stopwatch-in-reactjs-how-can-i-add-each-number-into-some-sort-of-array

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM