1 回答
TA贡献1835条经验 获得超7个赞
这使用了Children API,该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>
)}
/>
);
}
添加回答
举报