安裝 Tailwind CSS
npm install -D tailwindcss
npx tailwindcss init
tailwind.config.js
module.exports = {
content: [
"./templates/**/*.{html,js}",
"./static/**/*.{html,js}",
],
theme: {
extend: {},
},
plugins: [],
}
static/styles.css
@tailwind base;
@tailwind components;
@tailwind utilities;
index.html
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>第二十天 - 優化前端界面</title>
<link rel="stylesheet" href="/static/styles.css">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body class="bg-gray-100 text-gray-800">
<div id="root" class="container mx-auto p-4"></div>
<script src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script type="text/babel">
function App() {
const [chartData, setChartData] = React.useState(null);
React.useEffect(() => {
fetch('/api/chart-data')
.then(response => response.json())
.then(data => setChartData(data));
}, []);
React.useEffect(() => {
if (chartData) {
const ctx = document.getElementById('myChart').getContext('2d');
new Chart(ctx, {
type: 'bar',
data: chartData,
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
}
}, [chartData]);
return (
<div className="bg-white shadow rounded-lg p-6">
<h1 className="text-2xl font-bold mb-4">第二十天 - 優化前端界面</h1>
<canvas id="myChart"></canvas>
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
</script>
</body>
</html>
安裝 React Router
npm install react-router-dom
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
function App() {
return (
<Router>
<Switch>
<Route path="/" exact>
<Home />
</Route>
<Route path="/about">
<About />
</Route>
</Switch>
</Router>
);
}
function Home() {
return <h1>首頁</h1>;
}
function About() {
return <h1>關於我們</h1>;
}
ReactDOM.render(<App />, document.getElementById('root'));
大概的結構圖會長這樣
app.py
templates/index.html
static/styles.css