首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >从另一个页面上的函数调用function钩子

从另一个页面上的函数调用function钩子
EN

Stack Overflow用户
提问于 2021-12-12 00:34:40
回答 1查看 729关注 0票数 0

我正在下国际象棋,我需要整合一个倒计时器,例如,当白色玩家打开他们的时钟,直到他们移动为止。

为了避免更改这个问题中不存在的更多代码,我想保持函数“移动”的原样,不过如果需要,我可以更改CountDownTimer,

现在,我想知道如何从函数移动调用CountDownTimer组件中的react,然后我可以自己计算出其余的。

据我所知,你不能用反应钩来做这件事吗?所以,只要寻找任何有用的东西,如果这意味着改变CountDownTimer。

代码语言:javascript
代码运行次数:0
运行
复制
export function move(from, to, promotion) {


    let tempMove = { from, to }

        if (member.piece === chess.turn()) {
            const legalMove = chess.move(tempMove)
            if (legalMove) {
                updateGame()


        //i would like to access CountDownTimer and call setTimerOn(true) 
// i can work out the code for white and black / start and stop myself afterwards


            }
        } 
,


}
代码语言:javascript
代码运行次数:0
运行
复制
import React from 'react'

function CountDownTimer(){

  const [time, setTime] = React.useState(0);
  const [timerOn, setTimerOn] = React.useState(false);

  React.useEffect(() => {
    let interval = null;

    if (timerOn) {
      interval = setInterval(() => {
        setTime((prevTime) => prevTime + 10);
      }, 10);
    } else if (!timerOn) {
      clearInterval(interval);
    }

    return () => clearInterval(interval);
  }, [timerOn]);

  return (
    <div className="Timers">
      <h2>Stopwatch</h2>
      <div id="display">
        <span>{("0" + Math.floor((time / 60000) % 60)).slice(-2)}:</span>
        <span>{("0" + Math.floor((time / 1000) % 60)).slice(-2)}:</span>
        <span>{("0" + ((time / 10) % 100)).slice(-2)}</span>
      </div>

      <div id="buttons">
        {!timerOn && time === 0 && (
          <button onClick={() => setTimerOn(true)}>Start</button>
        )}
        {timerOn && <button onClick={() => setTimerOn(false)}>Stop</button>}
        {!timerOn && time > 0 && (
          <button onClick={() => setTime(0)}>Reset</button>
        )}
        {!timerOn && time > 0 && (
          <button onClick={() => setTimerOn(true)}>Resume</button>
        )}
      </div>
    </div>
  );
});

export default CountDownTimer; ```
EN

回答 1

Stack Overflow用户

发布于 2021-12-12 01:59:07

在React文档的基础上,可以从函数组件或其他钩子调用React。

在您的情况下,您应该考虑使用React上下文。您需要将timerOn状态和setTimerOn方法提升为上下文值。这样,由上下文提供程序包装的所有组件都可以利用这些值。

首先,为管理上下文创建一些助手。

代码语言:javascript
代码运行次数:0
运行
复制
// TimerOn.js

import React, { createContext, useContext } from 'react';

// create a context
const TimerOnContext = createContext();

// create a hook to provide context value
export function useTimerOn() {
  const contextValue = useContext(TimerOnContext);
  return contextValue;
}

// custom provider that will wrap your main components
export function TimerOnProvider({ children }) {
  const [timerOn, setTimerOn] = React.useState(false);

  return (
    <TimerOnContext.Provider value={{ timerOn, setTimerOn }}>
      {children}
    </TimerOnContext.Provider>
  );
}

例如,我创建了两个简单的组件来演示timer组件和调用者组件。

代码语言:javascript
代码运行次数:0
运行
复制
// CountDownTimer.js

import React from "react";
import { useTimerOn } from "./TimerOn";

export default function CountDownTimer() {
  const { timerOn } = useTimerOn();

  // detect changes
  React.useEffect(() => {
    if (timerOn) {
      console.log('timer is on');
    } else {
      console.log('timer is off');
    }
  }, [timerOn]);

  return (
    <div>{timerOn ? 'timer on' : 'timer off'}</div>
  );
}
代码语言:javascript
代码运行次数:0
运行
复制
// MoveCaller.js   

import React from "react";
import { useTimerOn } from "./TimerOn";

export default function MoveCaller() {
  const { timerOn, setTimerOn } = useTimerOn();

  // move then set timer
  const move = () => {
    setTimerOn(!timerOn);
  }

  return (
    <div>
      <button type="button" onClick={move}>
        Move
      </button>
    </div>
  );
}

然后,可以使用提供程序组件包装所有主要组件。因此,组件中的move函数可以更改timerOn的状态并由另一个组件读取。

代码语言:javascript
代码运行次数:0
运行
复制
import React from 'react';
import CountDownTimer from './CountDownTimer';
import MoveCaller from './MoveCaller';
import { TimerOnProvider } from './TimerOn';

export default function ChessApp() {

  return (
    <TimerOnProvider>
      <CountDownTimer />
      <MoveCaller />
    </TimerOnProvider>
  );
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70320093

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档