react hook学生成绩
时间: 2023-08-30 15:11:12 浏览: 52
用于WebSocket通信的React Hook-React开发
以下是一个使用React Hook的学生成绩管理应用示例:
```jsx
import React, { useState } from 'react';
const StudentScoreApp = () => {
const [students, setStudents] = useState([
{ id: 1, name: 'Alice', score: 90 },
{ id: 2, name: 'Bob', score: 80 },
{ id: 3, name: 'Charlie', score: 70 },
]);
const [newStudentName, setNewStudentName] = useState('');
const [newStudentScore, setNewStudentScore] = useState('');
const addStudent = () => {
const newStudent = {
id: students.length + 1,
name: newStudentName,
score: parseInt(newStudentScore),
};
setStudents([...students, newStudent]);
setNewStudentName('');
setNewStudentScore('');
};
const deleteStudent = (id) => {
setStudents(students.filter((student) => student.id !== id));
};
const averageScore = () => {
const totalScore = students.reduce((acc, student) => acc + student.score, 0);
return totalScore / students.length;
};
return (
<div>
<h1>Student Scores</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Score</th>
<th></th>
</tr>
</thead>
<tbody>
{students.map((student) => (
<tr key={student.id}>
<td>{student.id}</td>
<td>{student.name}</td>
<td>{student.score}</td>
<td>
<button onClick={() => deleteStudent(student.id)}>Delete</button>
</td>
</tr>
))}
</tbody>
</table>
<div>
<input
type="text"
placeholder="Name"
value={newStudentName}
onChange={(e) => setNewStudentName(e.target.value)}
/>
<input
type="number"
placeholder="Score"
value={newStudentScore}
onChange={(e) => setNewStudentScore(e.target.value)}
/>
<button onClick={addStudent}>Add</button>
</div>
<p>Average Score: {averageScore()}</p>
</div>
);
};
export default StudentScoreApp;
```
这个应用中使用了两个React Hook:useState和useEffect。useState用于管理学生列表、新学生的输入以及删除学生的操作。useEffect可以用于在组件挂载时从后台获取学生列表数据。
阅读全文