【问题标题】:Adding event handlers dynamically based on className基于 className 动态添加事件处理程序
【发布时间】:2020-03-06 18:15:56
【问题描述】:

我有一个 React 函数组件,其中我在 props 中获得了另一个组件。像这样的:

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 变量中为类clickable 的元素动态添加事件处理程序呢? 提前感谢您的帮助。

【问题讨论】:

  • 你希望你的 onClick 处理程序在哪里,你的 ParentComponent 还是你的 ChildComponent?
  • 在子组件中

标签: javascript reactjs


【解决方案1】:

这使用Children API,允许您根据其当前道具修改儿童道具。 ChildComponent 将首先遍历其当前子组件,查找 clickable className 道具并将 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>
      )}
    />
  );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-04
    • 2014-07-06
    • 2016-06-06
    • 1970-01-01
    • 2011-04-25
    • 1970-01-01
    • 2015-02-26
    • 2017-03-15
    相关资源
    最近更新 更多