React迭代场景下如何传递onClick事件给父组件以删除表格行
Got it, let's work through this row deletion issue together! The core problem here is passing the parent's delete handler down to the child row elements correctly—without messing up your table structure. Here's how to do it step by step:
1. Update the Parent's Delete Handler
First, let's make your handleDelete method actually target and remove the right row. We'll have it accept an index (or a unique ID if your data objects have one) to specify which row to delete:
class Home extends Component { constructor(props) { super(props); this.state = { data: []}; // Bind the handler to ensure `this` refers to the component instance this.handleDelete = this.handleDelete.bind(this); } handleDelete(index) { // Use filter to create a new array excluding the targeted row (never mutate state directly!) this.setState(prevState => ({ data: prevState.data.filter((_, i) => i !== index) })); } render() { return ( <div> {/* Pass the delete handler as a prop to TableTasks */} <TableTasks data={this.state.data} header={[{ name: "No"}, { name: "Delete" }]} onDelete={this.handleDelete} /> </div> ); } }
2. Pass the Handler to the Row Renderer
Next, update your TableTasks component to receive the onDelete prop and pass it along to the row function, along with the current row's index:
const row = (props, i, onDelete) => ( <TableRow key={`thr-${i}`}> <TableRowColumn> {props.nameTask} </TableRowColumn> <TableRowColumn className="DeleteButton"> {/* Wrap onDelete in an arrow function to trigger it only on click */} <IconButton onClick={() => onDelete(i)}> <DeleteIcon /> </IconButton> </TableRowColumn> </TableRow> ); export const TableTasks = ({ data, header, onDelete }) => ( <Table> <TableHeader> <TableRow> {header.map((x, i) => ( <TableHeaderColumn key={`thc-${i}`}> {x.name} </TableHeaderColumn> ))} </TableRow> </TableHeader> <TableBody> {/* Pass the onDelete handler and row index to the row function */} {data.map((x, i) => row(x, i, onDelete))} </TableBody> </Table> );
Key Things to Note:
- Arrow function in
onClick: If we wroteonClick={onDelete(i)}, it would run immediately when the row renders. Wrapping it in an arrow function ensures it only triggers when the button is clicked. - No need to turn
rowinto a full component: Keeping it as a simple render function preserves your table's original structure, which avoids the layout issues you ran into earlier. - Immutable state update: We use
filterinstead ofsplicebecause React requires us to never mutate state directly—filtercreates a new array without the deleted row, which is the correct pattern for state updates.
That's it! Now when you click the delete icon in any row, it will trigger the parent's handleDelete method, update the state, and the table will re-render without the deleted row.
内容的提问来源于stack exchange,提问作者Italik

