React - 在作为道具传递的点击处理程序中传递组件 prop



我是 React 的新手。我有一个这样的反应组件Child-

//this.props has obj = {'id': 123, 'name': 'abc'}
class Child extends React.Component{
constructor(props){
super(props);
}
render(){
return(
<div onClick={this.props.remove}></div>
);
}
}

此组件是从某个Parent组件中使用的,该组件具有此类Child组件的列表,每个组件都有自己的this.props.objthis.props.remove是从Parent传递给Child的另一个处理程序。

现在,单击从组件中重新提取divChild我想在删除函数中传递this.props.obj.id。我该怎么做。

谢谢

欢迎来到 React!

可以在此处了解事件处理程序

我会这样写;

class Child extends React.Component{
constructor(props){
super(props);
}
handleClick({id}) {
this.props.remove(id)
}
render(){
const obj = this.props
return(
<div onClick={() => this.handleClick(obj)}></div>
);
}
}

您可以使用箭头函数来实现此目的。

class Child extends React.Component{
constructor(props){
super(props);
}
render(){
return(
<div onClick={() => this.props.remove(this.props.obj.id)}></div>
);
}
}

最新更新