繁体   English   中英

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

[英]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.

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