【问题标题】:Get all child component hrefs using a React higher-order component使用 React 高阶组件获取所有子组件 href
【发布时间】:2019-05-20 19:52:13
【问题描述】:

我的目标是在所有带有链接到外部域的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;

孩子嵌套任意深。

我如何捕获每一个,以便我可以将点击处理程序附加到它?

【问题讨论】:

    标签: javascript reactjs higher-order-components


    【解决方案1】:

    好吧,这个比较乱,我们用React.Children API遍历所有react元素,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>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-26
      • 2019-04-01
      • 2018-02-06
      • 2019-12-15
      • 2019-09-25
      • 1970-01-01
      • 1970-01-01
      • 2018-11-18
      相关资源
      最近更新 更多