咒語 用 mui 寫一個頁面 來決定吃甚麼 先給十筆台灣常見的假資料 並且可以有個輸入 幫我算出各項百分比 要依據輸入變動
import React, { useState, useEffect } from "react";
import { Button, TextField, Typography, Container, Grid } from "@mui/material";
function Roulette() {
const [foodList, setFoodList] = useState([
"牛肉麵",
"滷肉飯",
"排骨便當",
"拉麵",
"披薩",
"炸雞",
"壽司",
"炒麵",
"三明治",
"鍋貼",
]);
const [newFood, setNewFood] = useState("");
const [selectedFood, setSelectedFood] = useState(null);
// 計算總食物項數量
const totalFoodCount = foodList.length;
// 計算每個食物項的百分比
const foodPercentages = foodList.map(() => (1 / totalFoodCount) * 100);
const handleAddFood = () => {
if (newFood.trim() !== "") {
setFoodList([...foodList, newFood]);
setNewFood("");
}
};
const handleRandomSelection = () => {
const randomIndex = Math.floor(Math.random() * foodList.length);
setSelectedFood(foodList[randomIndex]);
};
return (
<Container>
<Typography variant="h4" align="center" gutterBottom>
食物輪盤
</Typography>
<Grid container spacing={2}>
<Grid item xs={12} sm={6}>
<TextField
label="輸入新食物"
variant="outlined"
fullWidth
value={newFood}
onChange={(e) => setNewFood(e.target.value)}
/>
</Grid>
<Grid item xs={12} sm={6}>
<Button
variant="contained"
color="primary"
onClick={handleAddFood}
fullWidth
>
添加食物
</Button>
</Grid>
</Grid>
<div style={{ marginTop: "20px" }}>
<Button
variant="contained"
color="primary"
onClick={handleRandomSelection}
>
隨機選擇食物
</Button>
</div>
{selectedFood && (
<Typography variant="h5" align="center" style={{ marginTop: "20px" }}>
今天吃:{selectedFood}
</Typography>
)}
<Typography variant="h6" style={{ marginTop: "20px" }}>
各食物百分比:
</Typography>
<ul>
{foodList.map((food, index) => (
<li key={index}>
{food}: {foodPercentages[index].toFixed(2)}%
</li>
))}
</ul>
</Container>
);
}
export default Roulette;
這樣就可以決定今晚吃啥了 祝各位放假愉快