我想在点击事件后删除表格行。我已经创建了迭代并显示了删除按钮,但不知道在我的情况下如何将 onClick 事件从父组件传递到子组件。
我尝试将 const row
更改为 component
并像往常一样传递 onClick,但此方法会破坏我的表。
父组件:
class Home extends Component {
constructor(props) {
super(props);
this.state = { data: []};
}
handleDelete{
alert('here I want to have code to remove row from table')
}
render() {
return (
<div>
<TableTasks data={this.state.data} header={[{ name: "No"}, { name: "Delete" }]} />
</div>
);
}}
子组件:
const row = (props, i) =>
<TableRow key={`thr-${i}`}>
<TableRowColumn>
{props.nameTask}
</TableRowColumn>
<TableRowColumn className="DeleteButton">
<IconButton>
<DeleteIcon onClick={?????}/>
</IconButton>
</TableRowColumn>
</TableRow>;
export const TableTasks = ({ data, header }) =>
<Table>
<TableHeader>
<TableRow>
{header.map((x, i) =>
<TableHeaderColumn key={`thc-${i}`}>
{x.name}
</TableHeaderColumn>
)}
</TableRow>
</TableHeader>
<TableBody>
{data.map((x, i) => row(x, i))}
</TableBody>
</Table>;
最佳答案
步骤:
1- 将 handleDelete
函数从父级传递给子级 TableTasks
组件:
<TableTasks handleDelete={this.handleDelete} .... />
2- 在父级定义handleDelete
:
handleDelete(){....}
3- handleDelete
将在 TableTasks
组件中可用,像数据一样解构它:
export const TableTasks = ({ data, header, handleDelete }) => {...}
4- 现在将 handleDelete
传递给 row
函数:
{data.map((x, i) => row(x, i, handleDelete))}
5- 现在 handleDelete
将可用:
const row = (props, i, handleDelete) => {
console.log('handleDelete', handleDelete);
return (
....
<DeleteIcon onClick={handleDelete} />
....
)
}
关于javascript - 在 ReactJS 中使用迭代时如何将 onClick 事件传递给父组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48062580/