简体   繁体   English

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

[英]React - passing component prop in click handlers passed as props

I am new to React.我是 React 的新手。 I have a react component Child like this -我有一个像这样的反应组件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>
        );
    }
}

This component is being used from some Parent component which has a list of such Child component, each having their own this.props.obj .这个组件是从一些Parent组件中使用的,它有一个这样的Child组件列表,每个子组件都有自己的this.props.obj this.props.remove is another handler passed to Child from Parent . this.props.remove是另一个从Parent传递给Child的处理程序。

Now, on click of div redered from Child component, I want to pass this.props.obj.id in remove function.现在,在单击从Child组件重新生成的div时,我想将this.props.obj.id传递给删除 function。 How can I do that.我怎样才能做到这一点。

Thanks谢谢

Welcome to React!欢迎来到反应!

You can learn about event handlers here您可以在此处了解事件处理程序

I would write it up like this;我会这样写;

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>
        );
    }
}

You can use arrow functions to achieve this.您可以使用箭头函数来实现这一点。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM