使用React高阶组件获取所有子组件href

时间:2019-05-20 19:52:13

标签: javascript reactjs higher-order-components

我的目标是在所有带有链接到外部域的href的锚元素上添加点击处理程序。

这是我的组件:

import React from 'react';
import LinkWrapper from './LinkWrapper'

function ComponentWithLinks() {
  return (
    <div>
      <div>
        <ul>
          <li>
            <a href="/">internal link</a>
          </li>
          <li>
            <a href="http://example.com/external">external link</a>
          </li>
        </ul>
      </div>
      <div>
        <p>
          <a href="http://google.com">another external link</a>
        </p>
      </div>
    </div>
  );
}

const wrapped = LinkWrapper(ComponentWithLinks)

export default wrapped;

这是我的包装纸:

import React from 'react';

function LinkWrapper(WrappedComponent) {
  return class extends React.Component {
    render() {
      return <WrappedComponent {...this.props} />;
    }
  }
}

export default LinkWrapper;

孩子们被任意嵌套在深处。

如何捕获每个人,以便可以在其上附加点击处理程序?

1 个答案:

答案 0 :(得分:0)

好吧,这很麻烦,我们将使用React.Children API遍历所有反应元素,并使用React.createElement注入属性(在这种情况下为onClick)。

const injectToChildren = (children, addOnClickToAnchors) =>
  React.Children.map(children, addOnClickToAnchors);

const injectToAnchor = child =>
  React.cloneElement(child, { onClick: () => console.log('New Click') });

const addOnClickToAnchors = child => {
  const children = child.props.children;

  // Recursion end condition
  if (!children) return;

  const isAnchor = child.type === 'a';

  return isAnchor
    ? injectToAnchor(child)
    : {
        ...child,
        // Recursion step
        props: { children: injectToChildren(children, addOnClickToAnchors) }
      };
};

function ComponentWithLinks({ children }) {
  // Map every children recursively
  return injectToChildren(children, addOnClickToAnchors)
}

function App() {
  return (
    <ComponentWithLinks>
      // All kinds of children components
    </ComponentWithLinks>
  );
}

Edit Inject All Tree