【发布时间】:2021-02-26 16:43:32
【问题描述】:
我正在 React 中构建一个 CRUD 应用程序(类似于网络上的待办事项应用程序),但主要区别是我将每个条目附加到引导程序 Table。这可能不是表示数据的最佳方式,但它可以帮助我快速起步,而无需复习一些我很不擅长的 CSS 样式。
我的目标是能够在出现警告提示后删除Table 中的任何给定条目。但是,我不确定执行此操作的最佳方法。所以这里是Form来输入玩家的名字:
import React, { useState } from "react";
import { Form, Button } from "react-bootstrap";
const PlayerForm = ({ addPlayer }) => {
const [name, setName] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
addPlayer(name);
setName("");
};
return (
<Form onSubmit={handleSubmit}>
<Form.Group controlId="name">
<Form.Label>Name</Form.Label>
<Form.Control
required
type="text"
value={name}
placeholder="Normal text"
onChange={(e) => setName(e.target.value)}
/>
</Form.Group>
<Button type="submit">Add Player</Button>
</Form>
);
};
export default PlayerForm;
然后,数据进入PlayerList 组件:
import React, { useState } from "react";
import { v4 as uuidv4 } from "uuid";
import { Table, Form } from "react-bootstrap";
import PlayerForm from "./PlayerForm";
import styled from "styled-components";
const StyledInput = styled(Form.Control)`
padding: 2px 5px;
width: 60px;
height: 30px;
`;
const PlayerList = () => {
const [players, setPlayers] = useState([
{ name: "Harry Kane", country: "England", id: 1, goals: 0, percentage: 0 },
{
name: "Marcus Rashford",
country: "England",
id: 2,
goals: 0,
percentage: 0,
},
]);
const addPlayer = (name) => {
setPlayers([
...players,
{ name: name, id: uuidv4(), country: "England", goals: 0, percentage: 0 },
]);
};
return (
<div>
<Table>
<thead>
<tr>
<th>Name</th>
<th>Total Goals</th>
<th>Goal Percentage</th>
</tr>
</thead>
<tbody>
{players.map((player) => (
<tr key={player.id}>
<td>{player.name}</td>
<td>
<Form>
<Form.Group controlId="goals">
<StyledInput
size="sm"
required
type="number"
defaultValue={player.goals}
step={1}
className="smaller-input"
min="0"
/>
</Form.Group>
</Form>
</td>
<td>
<Form>
<Form.Group controlId="goals">
<StyledInput
size="sm"
required
type="number"
defaultValue={player.percentage}
step={1}
className="smaller-input"
min="0"
/>
</Form.Group>
</Form>
</td>
</tr>
))}
</tbody>
</Table>
<PlayerForm addPlayer={addPlayer} />
</div>
);
};
export default PlayerList;
现在我希望能够在将任何给定播放器添加到Table 后删除它们。除了构建函数,我不确定如何继续
const removePlayer =() =>{
}
有人可以帮我解决这个问题吗?
【问题讨论】:
标签: javascript reactjs react-hooks react-bootstrap styled-components