javascript - 基于 className 动态添加事件处理程序
问题描述
我有一个 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 变量中动态地将事件处理程序添加到具有可点击类的元素?预先感谢您的帮助。
解决方案
这使用了Children API,它允许您根据当前的 props 修改孩子的 props。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>
)}
/>
);
}
推荐阅读
- docker - 如何将 Github 连接到谷歌云平台?
- python - matlpotlib 中的标准化颜色映射到底发生了什么?
- javascript - 如何在下面的代码中摆脱 RequestOptionsArgs
- python - 使用外部数据库操作时,Django RestFramework 中需要序列化程序
- android - 无法解析大部分来自 AndroidX 的类
- python-3.x - 循环遍历数据框以搜索子字符串并更改大表上的列
- node.js - 在 NodeJs 中检索 Azure 环境变量
- javascript - Nuxt:每个会话显示一次启动动画
- react-native - 当标签比屏幕宽度更拟合时,提供一个react Antive Tabnavigator的溢出菜单
- java - 如何将链接存储到速度变量中并在 html 中显示?