首页 > 解决方案 > 无法将 ref 添加到克隆的元素

问题描述

我正在尝试克隆一个子组件并向它添加一个引用,如下所示:

let targetChild = null;
React.Children.forEach(children, (child, index) => {
    if (child.type.displayName === 'TargetChildElement') {
        targetChild = React.cloneElement(child, { ref: index });
    }
});

但是,当子元素正常工作时出现错误:

Uncaught Error: Function components cannot have refs. Did you mean to use React.forwardRef()?.

有谁知道我能做些什么来解决这个问题?

标签: reactjs

解决方案


推荐阅读