feat: 新增 node-frontend-react-function 示例(React 19 函数组件 + Hooks,Tengine 托管)

This commit is contained in:
2026-11-15 11:58:42 +08:00
parent cd1c155256
commit abb39ea291
18 changed files with 587 additions and 0 deletions
@@ -0,0 +1,4 @@
dist/
node_modules/
.git/
.DS_Store
@@ -0,0 +1,3 @@
dist/
node_modules/
npm-debug.log*
@@ -0,0 +1,23 @@
# 编译阶段:compile-node22(Vite 7 需要 Node >= 20.19)
FROM registry.cn-shanghai.aliyuncs.com/odboy/kenaito:compile-node22 AS build
WORKDIR /src
COPY package.json package-lock.json* ./
# npm 源由镜像的 /usr/local/node/etc/npmrc 指向 npmmirror,无需额外换源
RUN npm install --no-audit --no-fund
COPY . ./
RUN npm run build && ls -lh dist/ dist/assets/
# 运行阶段:Tengine 3.1.0(自建 proxy-tengine3 镜像)托管静态文件
FROM registry.cn-shanghai.aliyuncs.com/odboy/kenaito:proxy-tengine3 AS runtime
LABEL MAINTAINER="tianjun@odboy.cn"
ENV TimeZone=Asia/Shanghai
# 站点配置与构建产物都放进镜像:conf.d/*.conf 由主配置 include,html/ 为站点根目录
COPY nginx/node-frontend-react-function.conf /usr/local/nginx/conf/conf.d/node-frontend-react-function.conf
COPY --from=build /src/dist/ /usr/local/nginx/html/
# 构建期自检:配置语法错误直接让镜像构建失败;纯静态站点没有上游主机名,nginx -t 可直接通过
RUN /usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
EXPOSE 80
STOPSIGNAL SIGQUIT
CMD ["/usr/local/nginx/sbin/nginx", "-g", "daemon off;"]
@@ -0,0 +1,70 @@
# node-frontend-react-function 示例
React 19 **函数组件 + Hooks** 写法的前端项目,**构建阶段**用 `compile-node22` 跑 Vite,**运行阶段**以自建
`proxy-tengine3` 镜像为基座托管静态文件。类组件写法见同级的
[`node-frontend-react-class`](../node-frontend-react-class/README.md),两者页面与部署方式完全一致,只差组件写法。
| 阶段 | 镜像 | 说明 |
| --- | --- | --- |
| 编译 | `registry.cn-shanghai.aliyuncs.com/odboy/kenaito:compile-node22` | Node 22 + npm(源为 npmmirror),Vite 7 要求 Node ≥ 20.19 |
| 运行 | `registry.cn-shanghai.aliyuncs.com/odboy/kenaito:proxy-tengine3` | Tengine 3.1.0,托管 `dist/` |
纯前端项目:页面数据全部在浏览器内产生,不调用任何后端接口,部署只需要一个 Tengine 容器。
### 示例内容
```
node-frontend-react-function/
├── package.json # react 19.3.1 / react-dom 19.3.1;vite 7 + plugin-react 5
├── vite.config.js # base: './';react/react-dom 单独拆包
├── index.html
├── src/
│ ├── main.jsx # createRoot + StrictMode
│ ├── App.jsx # 顶部页签(useState 切换视图,不引路由库)
│ ├── styles.css # 轻量手写样式,不引 UI 库
│ └── views/
│ ├── Home.jsx # useState/useEffect:计数器、时钟、受控输入
│ ├── Form.jsx # 受控表单 + 手写校验(含错误提示与提交结果)
│ └── About.jsx # 版本与部署说明
├── nginx/
│ └── node-frontend-react-function.conf # Tengine 站点配置:静态托管 + /healthz
├── Dockerfile # 两阶段:compile-node22 -> proxy-tengine3
├── build.sh # 构建镜像(PUSH=1 时同时推送)
├── docker-compose.yml # 只部署前端(端口 8091)
├── startup.sh / shutdown.sh
└── .dockerignore / .gitignore
```
### 构建与部署
```shell
sh build.sh # docker build -t registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-node-frontend-react-function .
PUSH=1 sh build.sh # 构建并推送
sh startup.sh # docker-compose -f docker-compose.yml -p node-frontend-react-function-demo up -d
```
访问 http://127.0.0.1:8091/ ;`curl http://127.0.0.1:8091/healthz` 返回 `ok`。
### 本地开发(不用 docker)
```shell
npm install
npm run dev # http://127.0.0.1:5373
```
### 关键点
**函数组件写法**:视图全部是函数组件,状态用 `useState`、副作用用 `useEffect`(时钟的定时器在
cleanup 里 `clearInterval`),表单用受控输入 + `useState` 校验。这是 React 16.8 之后的推荐写法。
**不引路由库 / UI 库**:三个视图用 `useState` 切换,样式手写在 `src/styles.css`,依赖只有 react / react-dom。
**站点配置**:配置放在 `nginx/node-frontend-react-function.conf`,构建时 `COPY` 到 `/usr/local/nginx/conf/conf.d/`
(镜像自带 nginx.conf 已经 `include conf.d/*.conf`);compose 又把宿主机 `./nginx` 挂到同一个 `conf.d`。
挂目录而不是单文件:单文件挂载编辑会换 inode,容器内看不到改动。
### 停止
```shell
sh shutdown.sh
```
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env bash
# 在示例目录下构建示例镜像(编译 + 运行两阶段均在本机 docker 内完成)
set -euo pipefail
cd "$(dirname "$0")"
IMAGE=${IMAGE:-registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-node-frontend-react-function}
docker build -t "${IMAGE}" .
if [ "${PUSH:-0}" = "1" ]; then
docker push "${IMAGE}"
fi
@@ -0,0 +1,32 @@
version: '3.8'
# 网段避开其它示例(172.31.0/24 ~ 172.31.4/24 已被 go / rust / node-backend / node-frontend-vue2 / vue3 占用)
networks:
node-frontend-react-function-demo:
ipam:
driver: default
config:
- subnet: "172.31.5.0/24"
services:
frontend:
image: registry.cn-shanghai.aliyuncs.com/odboy/kenaito:demo-node-frontend-react-function # 镜像由 build.sh 构建
container_name: node-frontend-react-function-demo
restart: unless-stopped
ports: # 映射端口:前端页面
- "8091:80"
volumes: # 只挂载站点配置目录,改完 reload 即可,不必重建镜像
# 挂目录而不是单文件:单文件挂载在宿主机上编辑会换 inode,容器内看不到改动
- "./nginx:/usr/local/nginx/conf/conf.d"
environment: # 设置环境变量,相当于docker run命令中的-e
TZ: Asia/Shanghai
healthcheck:
# 运行镜像自带 net-tools,直接用端口探测
test: ["CMD-SHELL", "netstat -tln | grep -q ':80 '"]
interval: 30s
timeout: 5s
retries: 3
start_period: 5s
networks:
node-frontend-react-function-demo:
ipv4_address: 172.31.5.20
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>node-frontend-react-function | React 19 函数组件</title>
</head>
<body>
<div id="root"></div>
<script src="/src/main.jsx" type="module"></script>
</body>
</html>
@@ -0,0 +1,29 @@
# node-frontend-react-function 站点:Tengine 3.1.0 托管 React 构建产物(纯静态,无后端依赖)
server {
listen 80;
server_name _;
access_log /dev/stdout main;
root /usr/local/nginx/html;
index index.html;
# 静态资源带 hash,长缓存;index.html 每次重新验证,保证发版后立即生效
location /assets/ {
expires 30d;
add_header Cache-Control "public, immutable";
try_files $uri =404;
}
# 前端路由兜底:示例不引入路由库,保留是为了以后加 react-router 时不用改配置
location / {
try_files $uri $uri/ /index.html;
}
# 健康检查:直接读 index.html
location = /healthz {
access_log off;
default_type text/plain;
return 200 "ok\n";
}
}
@@ -0,0 +1,23 @@
{
"name": "node-frontend-react-function",
"version": "1.0.0",
"private": true,
"description": "React 19 前端示例,构建产物由 Tengine 托管",
"type": "module",
"engines": {
"node": ">=20.19"
},
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview --port 4173"
},
"dependencies": {
"react": "19.3.1",
"react-dom": "19.3.1"
},
"devDependencies": {
"@vitejs/plugin-react": "5.2.0",
"vite": "7.3.8"
}
}
+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")"
docker-compose -f docker-compose.yml -p node-frontend-react-function-demo down
@@ -0,0 +1,39 @@
import { useState } from 'react';
import Home from './views/Home.jsx';
import Form from './views/Form.jsx';
import About from './views/About.jsx';
const TABS = [
{ key: 'home', label: '首页', view: Home },
{ key: 'form', label: '表单', view: Form },
{ key: 'about', label: '关于', view: About },
];
// 示例不引入路由库:用一个受控 state 当页签,保持依赖最少;真实项目可换 react-router
export default function App() {
const [active, setActive] = useState('home');
const Current = TABS.find((t) => t.key === active).view;
return (
<div className="app">
<header className="header">
<span className="logo">node-frontend-react-function</span>
<nav className="nav">
{TABS.map((t) => (
<button
key={t.key}
type="button"
className={t.key === active ? 'nav-item active' : 'nav-item'}
onClick={() => setActive(t.key)}
>
{t.label}
</button>
))}
</nav>
</header>
<main className="main">
<Current />
</main>
</div>
);
}
@@ -0,0 +1,10 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.jsx';
import './styles.css';
createRoot(document.getElementById('root')).render(
<StrictMode>
<App />
</StrictMode>,
);
@@ -0,0 +1,156 @@
* {
box-sizing: border-box;
}
html,
body,
#root {
height: 100%;
margin: 0;
}
body {
font-family: -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif;
color: #303133;
background: #f5f7fa;
}
.header {
display: flex;
align-items: center;
gap: 24px;
height: 56px;
padding: 0 20px;
background: #fff;
border-bottom: 1px solid #ebeef5;
}
.logo {
font-size: 18px;
font-weight: 600;
color: #409eff;
}
.nav {
display: flex;
gap: 8px;
}
.nav-item {
padding: 6px 14px;
border: 1px solid transparent;
border-radius: 4px;
background: transparent;
color: #303133;
cursor: pointer;
}
.nav-item:hover {
color: #409eff;
}
.nav-item.active {
color: #409eff;
border-color: #d9ecff;
background: #ecf5ff;
}
.main {
padding: 20px;
}
.card {
background: #fff;
border: 1px solid #ebeef5;
border-radius: 4px;
padding: 20px;
}
.card + .card {
margin-top: 16px;
}
.card-title {
margin: 0 0 16px;
font-size: 16px;
font-weight: 600;
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
gap: 16px;
}
.kv {
width: 100%;
border-collapse: collapse;
}
.kv th,
.kv td {
padding: 6px 12px;
border: 1px solid #ebeef5;
text-align: left;
}
.kv th {
width: 40%;
background: #fafafa;
}
.clock {
margin: 0 0 12px;
font-size: 24px;
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.btn {
padding: 6px 14px;
border: 1px solid #dcdfe6;
border-radius: 4px;
background: #fff;
cursor: pointer;
}
.btn.primary {
color: #fff;
border-color: #409eff;
background: #409eff;
}
.field {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 14px;
}
.field label {
width: 80px;
text-align: right;
}
.field input,
.field select {
flex: 1;
max-width: 320px;
padding: 6px 10px;
border: 1px solid #dcdfe6;
border-radius: 4px;
}
.hint {
margin-top: 12px;
padding: 8px 12px;
border-radius: 4px;
background: #f0f9eb;
color: #67c23a;
}
.error {
margin-left: 8px;
color: #f56c6c;
font-size: 12px;
}
@@ -0,0 +1,16 @@
// 静态说明页,无逻辑
export default function About() {
return (
<div className="card">
<h3 className="card-title">关于</h3>
<table className="kv">
<tbody>
<tr><th>框架</th><td>React 19.3.1(函数组件 + Hooks)</td></tr>
<tr><th>构建</th><td>Vite 7 + @vitejs/plugin-react 5</td></tr>
<tr><th>部署</th><td>Tengine 3.1.0(proxy-tengine3 镜像)托管 dist/</td></tr>
<tr><th>页签</th><td>useState 控制,不引入 react-router;需要路由时自行添加</td></tr>
</tbody>
</table>
</div>
);
}
@@ -0,0 +1,68 @@
import { useState } from 'react';
const EMPTY = { name: '', type: '', enabled: true, date: '' };
// 受控表单 + 简单校验,不引入表单库
export default function Form() {
const [form, setForm] = useState(EMPTY);
const [errors, setErrors] = useState({});
const [result, setResult] = useState('');
const update = (key, value) => setForm((prev) => ({ ...prev, [key]: value }));
const validate = () => {
const next = {};
if (!form.name.trim()) next.name = '请输入名称';
if (!form.type) next.type = '请选择类型';
setErrors(next);
return Object.keys(next).length === 0;
};
const submit = (e) => {
e.preventDefault();
if (!validate()) return;
setResult(`已提交:${JSON.stringify(form)}`);
};
const reset = () => {
setForm(EMPTY);
setErrors({});
setResult('');
};
return (
<div className="card">
<h3 className="card-title">React 受控表单</h3>
<form onSubmit={submit} noValidate>
<div className="field">
<label htmlFor="name">名称</label>
<input id="name" value={form.name} onChange={(e) => update('name', e.target.value)} placeholder="请输入名称" />
{errors.name && <span className="error">{errors.name}</span>}
</div>
<div className="field">
<label htmlFor="type">类型</label>
<select id="type" value={form.type} onChange={(e) => update('type', e.target.value)}>
<option value="">请选择</option>
<option value="frontend">前端</option>
<option value="backend">后端</option>
</select>
{errors.type && <span className="error">{errors.type}</span>}
</div>
<div className="field">
<label htmlFor="enabled">启用</label>
<input id="enabled" type="checkbox" checked={form.enabled} onChange={(e) => update('enabled', e.target.checked)} />
</div>
<div className="field">
<label htmlFor="date">日期</label>
<input id="date" type="date" value={form.date} onChange={(e) => update('date', e.target.value)} />
</div>
<div className="field">
<label />
<button type="submit" className="btn primary">提交</button>{' '}
<button type="button" className="btn" onClick={reset}>重置</button>
</div>
</form>
{result && <div className="hint">{result}</div>}
</div>
);
}
@@ -0,0 +1,59 @@
import { useEffect, useState } from 'react';
import { version as reactVersion } from 'react';
function format(d) {
const p = (n) => String(n).padStart(2, '0');
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
}
// 纯前端展示:所有数据都在浏览器里产生,不调用任何后端接口
export default function Home() {
const [count, setCount] = useState(0);
const [clock, setClock] = useState(() => format(new Date()));
const [keyword, setKeyword] = useState('');
useEffect(() => {
const timer = setInterval(() => setClock(format(new Date())), 1000);
return () => clearInterval(timer);
}, []);
return (
<>
<div className="grid">
<div className="card">
<h3 className="card-title">运行时</h3>
<table className="kv">
<tbody>
<tr><th>React</th><td>{reactVersion}</td></tr>
<tr><th>构建</th><td>Vite 7 + @vitejs/plugin-react</td></tr>
<tr><th>路由</th><td>示例用 useState 页签,不引入路由库</td></tr>
</tbody>
</table>
</div>
<div className="card">
<h3 className="card-title">计数器(useState)</h3>
<p className="clock">{count}</p>
<button type="button" className="btn" onClick={() => setCount((c) => c - 1)}>-1</button>{' '}
<button type="button" className="btn primary" onClick={() => setCount((c) => c + 1)}>+1</button>{' '}
<button type="button" className="btn" onClick={() => setCount(0)}>重置</button>
</div>
<div className="card">
<h3 className="card-title">当前时间(useEffect)</h3>
<p className="clock">{clock}</p>
<span className="hint">前端本地时间,不请求后端</span>
</div>
</div>
<div className="card">
<h3 className="card-title">受控输入</h3>
<div className="field">
<label htmlFor="kw">关键字</label>
<input id="kw" value={keyword} onChange={(e) => setKeyword(e.target.value)} placeholder="输入关键字过滤,纯前端" />
</div>
{keyword && <div className="hint">已输入:{keyword}</div>}
</div>
</>
);
}
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")"
docker-compose -f docker-compose.yml -p node-frontend-react-function-demo up -d
docker-compose -f docker-compose.yml -p node-frontend-react-function-demo ps
@@ -0,0 +1,23 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
// 纯静态前端:产物由 Tengine 托管,base 用相对路径,部署到任意子路径都能跑
export default defineConfig({
plugins: [react()],
base: './',
server: {
host: '0.0.0.0',
port: 5373,
},
build: {
outDir: 'dist',
sourcemap: false,
rollupOptions: {
output: {
manualChunks: {
react: ['react', 'react-dom'],
},
},
},
},
});