feat(chapter3): add effect hook demo
Demonstrate resize subscriptions with cleanup and show an async effect that updates the Ant Design button state.
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
// src/app/demo/_components/effect.tsx
|
||||
// ...
|
||||
'use client';
|
||||
|
||||
import { Button } from 'antd';
|
||||
import { type FC, useEffect, useState } from 'react';
|
||||
|
||||
import $styles from './style.module.css';
|
||||
|
||||
const EffectDemo: FC = () => {
|
||||
const [ghost, setGhost] = useState<boolean>(false);
|
||||
const [width, setWidth] = useState(0);
|
||||
const [red, setRed] = useState<boolean>(false);
|
||||
|
||||
const toggleGhostBtn = () => setGhost(!ghost);
|
||||
useEffect(() => {
|
||||
const resizeHandle = () => {
|
||||
setWidth(window.innerWidth);
|
||||
console.log('浏览器宽度改变');
|
||||
};
|
||||
const frameId = requestAnimationFrame(resizeHandle);
|
||||
window.addEventListener('resize', resizeHandle);
|
||||
|
||||
return () => {
|
||||
cancelAnimationFrame(frameId);
|
||||
window.removeEventListener('resize', resizeHandle);
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
(
|
||||
async () => {
|
||||
await new Promise((resolve) => {
|
||||
setTimeout(() => {
|
||||
resolve('done');
|
||||
}, 1000);
|
||||
});
|
||||
setRed(ghost);
|
||||
}
|
||||
)();
|
||||
}, [ghost]);
|
||||
|
||||
useEffect(() => {
|
||||
console.log('只在第一次或重新渲染时触发');
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className={$styles.container}>
|
||||
<h2 className="text-center">useEffect Demo</h2>
|
||||
<p className="py-5 text-center">{ghost ? 'ghost' : '普通'}按钮</p>
|
||||
<div className="flex flex-col justify-center">
|
||||
<Button type="primary" onClick={toggleGhostBtn} ghost={ghost} danger={red}>
|
||||
切换按钮样式
|
||||
</Button>
|
||||
<p className="pt-5 text-center">宽度为: {width}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
export default EffectDemo;
|
||||
@@ -3,6 +3,8 @@
|
||||
import { FC } from 'react';
|
||||
import { Button } from 'antd';
|
||||
import StateDemo from './_components/state';
|
||||
import EffectDemo from './_components/effect';
|
||||
import RefDemo from './_components/ref';
|
||||
|
||||
import $styles from './page.module.css';
|
||||
|
||||
@@ -19,6 +21,12 @@ const DemoPage: FC = () => (
|
||||
<div className={$styles.demo}>
|
||||
<StateDemo />
|
||||
</div>
|
||||
<div className={$styles.demo}>
|
||||
<EffectDemo />
|
||||
</div>
|
||||
<div className={$styles.demo}>
|
||||
<RefDemo />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user