文档
Preact 计数器与随机名言
目标
用 Preact Hooks 实现计数器 + 随机名言获取,展示信号式状态管理和 useEffect 副作用。
完整代码
src/main.jsx
import { render } from 'preact';
import { App } from './app';
render(<App />, document.getElementById('app'));
src/app.jsx
import { useState, useEffect } from 'preact/hooks';
const quotes = [
'代码是写给人看的,顺便让机器运行。',
'Talk is cheap. Show me the code.',
'简单是可靠的先决条件。',
'任何傻瓜都能写出计算机能理解的代码,唯有优秀程序员才能写出人能理解的代码。',
];
export function App() {
const [count, setCount] = useState(0);
const [quote, setQuote] = useState(quotes[0]);
// 切换名言
const randomQuote = () => {
let idx;
do { idx = Math.floor(Math.random() * quotes.length); }
while (quotes[idx] === quote && quotes.length > 1);
setQuote(quotes[idx]);
};
// 副作用:标题随 count 变化
useEffect(() => {
document.title = `计数: ${count}`;
}, [count]);
return (
<main style={{ fontFamily: 'system-ui', maxWidth: 400, margin: '60px auto', textAlign: 'center' }}>
<h1>⚛️ Preact Demo</h1>
<div style={{ margin: '30px 0' }}>
<p style={{ color: '#666' }}>计数器</p>
<p style={{ fontSize: '3em', fontWeight: 'bold', margin: '10px 0' }}>{count}</p>
<div style={{ display: 'flex', gap: 10, justifyContent: 'center' }}>
<button
onClick={() => setCount(c => c - 1)}
style={btnStyle('#ef4444')}
>-1</button>
<button
onClick={() => setCount(0)}
style={btnStyle('#6b7280')}
>重置</button>
<button
onClick={() => setCount(c => c + 1)}
style={btnStyle('#22c55e')}
>+1</button>
</div>
</div>
<div style={{ background: '#f0f9ff', padding: 20, borderRadius: 12, marginTop: 30 }}>
<p style={{ fontStyle: 'italic', fontSize: '1.1em' }}>"{quote}"</p>
<button onClick={randomQuote} style={btnStyle('#3b82f6')}>
🎲 换一句
</button>
</div>
<p style={{ marginTop: 30, color: '#999', fontSize: '0.85em' }}>
运行于 Preact · 仅 3KB
</p>
</main>
);
}
function btnStyle(color) {
return {
background: color,
color: 'white',
border: 'none',
padding: '8px 16px',
borderRadius: 6,
cursor: 'pointer',
fontSize: '1em',
};
}
运行步骤
npm create vite@latest preact-demo -- --template preact
cd preact-demo
# 替换 src/app.jsx 内容
npm install
npm run dev
预期输出
- 页面展示计数器和名言卡片
- 点击 +/- 按钮计数变化
- 页面标题同步更新为 "计数: N"
- 点击"换一句"随机切换名言