如何在React中使用其他组件中使用按钮的组件中访问组件中的功能?
我正在使用 react-timer-hook 为我的React设置了一个秒表应用。因此,我得到了一个Timer.js文件,此秒表正在使用一个开始和暂停按钮。我在app.js中调用组件,以便计时器显示在所有页面上。我的下一步是在名为start.js的不同组件中设置该启动功能(在最后页面中的暂停),但我不知道如何将其传递给该组件。
这是我的app.js:
function App() {
return (
<Router>
<div className="App">
<Timer/>
<Routes>
<Route path="/" element={ <Start /> }></Route>
// Other routes
</Routes>
</div>
</Router>
);
}
export default App;
timer.js file:
function MyTimer({ expiryTimestamp }) {
const {
seconds,
minutes,
start,
pause,
} = useStopwatch({ expiryTimestamp, onExpire: () => console.warn('onExpire called') });
return (
<div className="timer">
<div className='timer-inside' >
<span>{minutes < '10' ? '0' + minutes : minutes}</span>:<span>{seconds < '10' ? '0' + seconds : seconds}</span>
</div>
<button onClick={start}>Start</button>
<button onClick={pause}>Pause</button>
</div>
);
}
export default function App() {
return (
<div>
<MyTimer/>
</div>
);
}
因此,基本上我想要&lt; button onclick = {start}&gt; start&lt;/button&gt;
sippet摘要在名为start.js,而不是the Timer.js本身。
I am using react-timer-hook to set up a stopwatch for my React Application. So I got a Timer.js file where this stopwatch is working with a start and pause button. I am calling the component in App.js so the timer shows up on all pages. My next step is to set up that start functionality in a different component named Start.js (and later on the pause in the final page), but I can't figure out how I can pass it to this component.
This is my App.js:
function App() {
return (
<Router>
<div className="App">
<Timer/>
<Routes>
<Route path="/" element={ <Start /> }></Route>
// Other routes
</Routes>
</div>
</Router>
);
}
export default App;
Timer.js file:
function MyTimer({ expiryTimestamp }) {
const {
seconds,
minutes,
start,
pause,
} = useStopwatch({ expiryTimestamp, onExpire: () => console.warn('onExpire called') });
return (
<div className="timer">
<div className='timer-inside' >
<span>{minutes < '10' ? '0' + minutes : minutes}</span>:<span>{seconds < '10' ? '0' + seconds : seconds}</span>
</div>
<button onClick={start}>Start</button>
<button onClick={pause}>Pause</button>
</div>
);
}
export default function App() {
return (
<div>
<MyTimer/>
</div>
);
}
So basically i want the <button onClick={start}>Start</button>
snippet to work in a file called Start.js, instead of the Timer.js itself.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果要渲染起始组件作为计时器的孩子,则可以传递从UseStopWatch挂钩类似
开始
的开始功能,但是,如果您想在应用程序上渲染它,则需要在应用程序上调用挂钩pass what you need on the components you need:
So in both components will have same data property.
希望它有帮助!
If you want to render the Start component as a children of Timer, you can pass the start function received from the useStopwatch hook like
And inside the Start
But, if you want to render it on App, you need to call the hook on App and pass what you need on the components you need:
So in both components will have same data property.
Hope it helps!