[英]React - passing component prop in click handlers passed as props
我是 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.obj
。 this.props.remove
是另一个从Parent
传递给Child
的处理程序。
现在,在单击从Child
组件重新生成的div
时,我想将this.props.obj.id
传递给删除 function。 我怎样才能做到这一点。
谢谢
欢迎来到反应!
我会这样写;
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>
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.