React开发:JSX代码编写与事件处理全解析
1. JSX条件测试的编写方法
1.1 使用立即调用的JavaScript函数编写条件测试
在编写条件测试时,可将其集成到立即调用的JavaScript函数中。调用该函数会立即生成要使用的JSX代码。以下是 Counter
组件的示例代码:
import { useState, useEffect } from "react";
function Counter({init, end}) {
init = parseInt(init || 0);
end = parseInt(end || 0);
const [count, setCount] = useState(init);
useEffect(function() {
if (end && count >= end) return;
var timer = setInterval(function() {
setCount((count)=>count+1);
}, 1000);
return function() {
clearInterval(timer);
}
});
return (
<>
Initial value of the counter is: {init}
<br />
End of the counter at: {end}
<br />