【发布时间】:2020-09-19 20:03:24
【问题描述】:
我有两个组件,一个是子组件,另一个是父组件。我有条件地渲染我的子组件。此代码的功能是当您单击按钮时将显示计时器,当您单击停止时计时器将停止。这里“定时器”是子组件,我在“定时器”组件中使用了状态属性,我想在单击“停止定时器按钮”之前显示定时器的值。那么如何将“计时器”状态变量值从子组件传递给父组件。
const[time,setTime]=useState(0);
const handleStart=()=>{
setTime(true);
}
const handleStop=()=>{
setTime(false);
}
.....
<button onClick={handleStart}>Start StopWatch</button>
<button onClick={handleStop}>Stop StopWatch</button>
{time?<Timer/>:null}
这是父组件,以下代码用于“计时器”组件。
import React,{useEffect,useState} from 'react';
const Timer = () => {
const[timer,setTimer]=useState(0);
useEffect(()=>{
setTimeout(()=>{
setTimer(prevTime=>prevTime+1);
},100)
},[timer])
let style={
position:"absolute",
height:"100px",
weight:"200px",
backgroundColor:"red",
zIndex:"1"
}
const handleStopTime=()=>{
console.log(timer);
setTimer(0);
}
return (
<div style={style}>
<h1>{timer}</h1>
</div>
);
}
export default Timer;
【问题讨论】:
-
不,但以下答案确实如此。
标签: javascript html reactjs react-hooks