Javascript 基于类名动态添加事件处理程序

Javascript 基于类名动态添加事件处理程序,javascript,reactjs,Javascript,Reactjs,我有一个React函数组件,在这里我在道具中得到另一个组件。大概是这样的: function ChildComponent({cmp}) { // Here onClick handlers should be added [for example: // () => console.log("clicked")] to all // elements in cmp of class .clickable return ... } function Pa

我有一个React函数组件,在这里我在道具中得到另一个组件。大概是这样的:

function ChildComponent({cmp}) {
    // Here onClick handlers should be added [for example:
    // () => console.log("clicked")] to all
    // elements in cmp of class .clickable

    return ...
}

function ParentComponent() {
    return (
        <ChildComponent cmp={<div><button>Non-clickable</button><button className="clickable">Clickable</button></div>} />
    )
}
那么,如何在ChildComponent的cmp props变量中动态地将事件处理程序添加到类可单击的元素中呢? 提前感谢您的帮助。

此API允许您根据当前的道具修改儿童道具。 ChildComponent将首先循环其当前子级,查找可单击的类名道具,并将onClick处理程序添加到其道具中

递归循环也允许嵌套的子对象工作

function ChildComponent({ cmp }) {
  const handleOnClick = () => {
    alert("Clicked");
  };

  const childrenMap = (child) => {
    if (child.props) {
      const newProps = Object.assign({}, child.props);
      const { children, className } = newProps;
      if (className && className.split(' ').some(cn => cn === 'clickable')) {
        newProps.onClick = handleOnClick;
      }
      if (children) {
        newProps.children = Children.map(children, childrenMap);
      }
      return cloneElement(child, newProps);
    }
    return child;
  }

  return Children.map(cmp, childrenMap);
}

function ParentComponent() {
  return (
    <ChildComponent
      cmp={(
        <div>
          <button>Non-clickable</button>
          <div>
            <div>
              <button className="clickable">Clickable</button>
            </div>
          </div>
          <button className="clickable">Clickable</button>
        </div>
      )}
    />
  );
}

您希望onClick处理程序位于何处,父组件还是子组件?在子组件中