猿问

根据 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 变量中动态地将事件处理程序添加到具有可点击类的元素?预先感谢您的帮助。


繁星淼淼
浏览 118回答 1
1回答

qq_花开花谢_0

这使用了Children API,该API 允许您根据当前的道具修改儿童的道具。ChildComponent 将首先循环遍历其当前子项,查找clickable className道具onClick并向其道具添加处理程序。递归循环也允许嵌套子项工作。function ChildComponent({ cmp }) {&nbsp; const handleOnClick = () => {&nbsp; &nbsp; alert("Clicked");&nbsp; };&nbsp; const childrenMap = (child) => {&nbsp; &nbsp; if (child.props) {&nbsp; &nbsp; &nbsp; const newProps = Object.assign({}, child.props);&nbsp; &nbsp; &nbsp; const { children, className } = newProps;&nbsp; &nbsp; &nbsp; if (className && className.split(' ').some(cn => cn === 'clickable')) {&nbsp; &nbsp; &nbsp; &nbsp; newProps.onClick = handleOnClick;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; if (children) {&nbsp; &nbsp; &nbsp; &nbsp; newProps.children = Children.map(children, childrenMap);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; return cloneElement(child, newProps);&nbsp; &nbsp; }&nbsp; &nbsp; return child;&nbsp; }&nbsp; return Children.map(cmp, childrenMap);}function ParentComponent() {&nbsp; return (&nbsp; &nbsp; <ChildComponent&nbsp; &nbsp; &nbsp; cmp={(&nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button>Non-clickable</button>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button className="clickable">Clickable</button>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button className="clickable">Clickable</button>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; )}&nbsp; &nbsp; />&nbsp; );}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答