首页 > 解决方案 > 通过单击调用停止时钟的“停止”功能

  • . 在组件之间传递函数“停止”
  • 问题描述

    预期效果:

    1. 单击名称 A。名称 A 处于活动状态
    2. 当我单击“Name B”元素时,我想调用“stopTimer ()”函数。在元素“Name A”中停止时间并运行函数“stopTimer()”

    当我单击诸如“名称 A”之类的元素时,名称 A 处于活动状态,在单击“名称 B”之前,我无法调用“stopTimer ()”函数

    当项目“名称 B”处于活动状态时,反之亦然。点击项目'Name A'调用函数'stopTimer()'

    这个解决方案有可能吗?我正在征求意见。

    更新:

    所有代码:https ://stackblitz.com/edit/react-kxuvgn

    我明白我的错误。我应该把函数stopTimer ()放在 parent 中App。当我单击时,stopTimer都需要该功能App

  • 停止时钟,以及在Stopwatch组件中插入stop按钮。我应该在哪里设置:{timerOn: false}); clearInterval (this.timer);这两个组件都很常见?

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

    应用程序

    class App extends React.Component {
      constructor() {
        super();
    
        this.state = {
          selectedTodoId: '',
          selectedTabId: null,
          items: [
            {
              id: 1,
              name: 'A',
              description: 'Hello'
            },
            {
              id: 2,
              name: 'B',
              description: 'World'
            }
          ],
          selectIndex: null
        };
      }
    
      stopTimer = (timer, timerOn) => {
        this.setState({ timerOn: timerOn });
        clearInterval(timer);
      };
    
       select = (id) => {
         if(id !== this.state.selectedTabId){
          this.setState({
            selectedTodoId: id,
            selectedTabId: id
          })
          this.stopTimer();
        }
      }
    
      isActive = (id) => {
        return this.state.selectedTabId === id;
      }
    
      render() {
    
        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}
                      isActive= {this.isActive(item.id)}
                    />
                  )
              }
            </ul>
             <ItemDetails
                items = {this.state.items}
                selectIndex = {this.state.selectIndex}
                resul={this.state.resul}
              />
              <Stopwatch
                stopTimer = {this.stopTimer}
              />
          </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} 
        </div>
    
    
        { (
        <button onClick={this.startTimer}>Start</button>
        )}
    
        {(
          <button onClick={this.stopTimer}>Stop</button>
        )}
    
        {this.state.timerOn === false && this.state.timerTime > 0 && (
          <button onClick={this.resetTimer}>Reset</button>
        )}
            </div>
          );
        }
    }
    
  • 标签: javascriptreactjs

    解决方案


    为此,您必须提升您的状态,在子卸载之前,将值传递给父组件进行存储。

    componentWillUnmount() {
      this.stopTimer();
      this.props.updateTimerTime(this.props.index, this.state.timerTime);
    }
    

    当子组件挂载时,从父组件传递的道具中设置状态。

    componentDidMount() {
      this.setState({
        timerTime: this.props.timerTime,
      });
    }
    

    Stackblitz 演示


    推荐阅读