首页 > 解决方案 > 在父组件中获取子组件的 onClick 道具

问题描述

我有一个父ButtonGroup组件和子buttonItem组件:

//ButtonGroup Component (Parent)

clicky(){
 //capture the props of the clicked button, ie, caption and disabled here.
}
render() {
  return (
    <div onClick={this.clicky}>
      {this.props.children}
    </div>
  )
}

//buttonItem component: 

render() {
  return (
    <button disabled={this.props.disabled}>{this.props.caption}</button>
  )
}

//final render
<ButtonGroupComponent>
  <buttonItem caption="Nothing"/>
  <buttonItem caption="Something" disabled={true}/>
  <buttonItem caption="Refresh"/>
</ButtonGroupComponent>

从上面的代码有什么办法可以捕捉到被点击的孩子的道具buttonItem

标签: reactjs

解决方案


在您的情况下,您需要this.props.children与您的自定义道具合并。所以,我建议你使用React.Children来操作它。顺便说一句,在添加新道具后,您需要返回这个孩子,所以 cloneElement会帮助您。

ButtonGroupComponent 的内部导入部分:

import React, { Children, Component, cloneElement } from 'react';

它的渲染函数将如下所示:

render() {  
    const childrenWithCustomHandler = Children.map(this.props.children, itemChild => {
       // Arguments of cloneElement (component, [customProps], [customChildren])
       return cloneElement(itemChild, { onClickItem: this.clicky })
     }
    );

    return <div>{childrenWithCustomHandler}</div>;
  }

组件的代码buttonItem如下所示:

 return (
    <button
      disabled={this.props.disabled}
      onClick={() => {
        this.props.onClickItem({ ...this.props });
      }}
    >
      {this.props.caption}
    </button>
  )

我使用Spread操作符来克隆对象,因此如果您想更改clicky函数中的道具,则不会呈现子对象。


推荐阅读