Refactored Working Code
App.js
import React, { Component } from "react";
import Table from "./Table";
class App extends Component {
state = {
characters: [
{
name: "Charlie",
job: "Janitor",
},
{
name: "Mac",
job: "Bouncer",
},
{
name: "Dee",
job: "Aspring actress",
},
{
name: "Dennis",
job: "Bartender",
},
],
};
removeCharacter = (index) => {
const { characters } = this.state;
this.setState({
characters: characters.filter((character, i) => {
return i !== index;
}),
});
};
render() {
const { characters } = this.state;
return (
<div className="container">
<Table
characterData={characters}
removeCharacter={this.removeCharacter}
/>
</div>
);
}
}
export default App;
Table.js
import React from "react";
const TableHeader = () => {
return (
<thead>
<tr>
<th>Name</th>
<th>Job</th>
</tr>
</thead>
);
};
const TableBody = (props) => {
const rows = props.characterData.map((row, index) => {
console.log(index);
return (
<tr key={index}>
<td>{row.name}</td>
<td>{row.job}</td>
<td>
<button onClick={() => props.removeCharacter(index)}>Delete</button>
</td>
</tr>
);
});
return <tbody>{rows}</tbody>;
};
class Table extends React.Component {
render() {
const Table = () => {
const { characterData, removeCharacter } = this.props;
return (
<table>
<TableHeader />
<TableBody
characterData={characterData}
removeCharacter={removeCharacter}
/>
</table>
);
};
return (
<div>
<Table />
</div>
);
}
}
export default Table;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…