我的目标是在所有带有链接到外部域的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;
孩子们被任意嵌套在深处。
如何捕获每个人,以便可以在其上附加点击处理程序?
答案 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>
);
}