[英]Pass props to component in ReactJS
I want to pass a variable from here:我想从这里传递一个变量:
let second = 0;
function timer() {
let res = second++;
console.log(res);
}
setInterval(timer, 1000);
function App() {
return (
<div>
<div className="timer">{timer()}</div>
</div>
);
}
This should return the seconds which are generated by the function timer
.这应该返回由 function
timer
生成的秒数。 In console log i got the result, but how to pass the seconds from the function to <div className="timer">{i want to pass here the seconds}</div>
?在控制台日志中,我得到了结果,但是如何将秒从 function 传递到
<div className="timer">{i want to pass here the seconds}</div>
? I tried to write <div className="timer">{timer()}</div>
, but it doesn't work.我试图写
<div className="timer">{timer()}</div>
,但它不起作用。 How to solve the issue?如何解决问题?
I don't know your development environment, but the following should be a working component that does what you want.我不知道您的开发环境,但以下应该是一个可以满足您需求的工作组件。
There are many things that may be considered bad practices in your code, beside the fact that, as you said, it doesn't work.除了正如您所说的那样,它不起作用之外,您的代码中有很多东西可能被认为是不好的做法。 I would suggest you to take the time to read at least once the ReactJS documentation.
我建议您花时间至少阅读一次 ReactJS 文档。
I don't even know if you know what State is, but in case you do, you're writing a functional component so you need to use Hooks to use the State.我什至不知道你是否知道 State 是什么,但如果你知道,你正在编写一个功能组件,所以你需要使用 Hooks 来使用 State。
import React, {useState, useRef} from 'react';
function Timer() {
const interval = useRef(null);
const [seconds, setSeconds] = useState(0);
return (
<div>
<div className="timer">{seconds}</div>
<button onClick={() => {
interval.current = setInterval(() => {
setSeconds(seconds + 1);
}, 1000);
}}>START</button>
<button onClick={() => {
clearInterval(interval.current);
interval.current = null;
setSeconds(0);
}}>CLEAR</button>
</div>
);
}
export default Timer;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.