我有一个功能组件,其中有一个计时器正在运行并且计时器会更新
var [时间,setTime] = useState(180000);
(我没有显示计时器的代码,因为我认为不需要它来回答我的问题)
这可以在 countDownTimer.js 中找到,如下所示
function CountDownTimer(props) {
var [time, setTime] = useState(180000);
}
然后在另一个选项卡中我有该功能
updateGame() {
}
有什么办法可以获取存储在的值
var [time, setTime] = useState(180000);
进入updateGame()
函数
我想要实现这样的目标
function CountDownTimer(props) {
[time, setTime] = useState(100);
export const GetTime = () => {
const time = time
return time
}
}
import {getTime} from "./countDownTimer.js"
updateGame() {
const time = getTime()
console.log(time)
//prints 100
}
愚蠢的尝试,但希望你明白了。
最佳答案
例如在父 App 组件中定义您的钩子(Hook),并将您的时间和 setTime 作为 prop 传递给 CountDownTimer 组件。将时间也传递给 UpdateGame 作为 Prop 。 在 CountDownTimer 中设置时间,也可以从 UpdateGame 中读取时间。
App.js
import {useState} from 'react'
import CountDownTimer from './CountDownTimer';
import UpdateGame from './UpdateGame';
function App() {
const [time, setTime] = useState(100);
return (
<div className="App">
<CountDownTimer time={time} setTime={setTime}></CountDownTimer>
<UpdateGame time={time}></UpdateGame>
</div>
);
}
export default App;
CountDownTimer.js
export default function CountDownTimer(props) {
const handleClick = ()=>{
props.setTime(200)
}
return (
<div>
<button onClick={handleClick}>{props.time}</button>
</div>
)
}
更新游戏.js
import React from 'react'
export default function UpdateGame(props) {
return (
<div>
{'time from updateGame: '+ props.time }
</div>
)
}
关于reactjs - 从功能组件外部获取 React Hook Value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70632850/