const ref = useRef()
React.Children.map(this.props.children, (element) => {
React.cloneElement(element, {
innerRef: node => ref,
})
})
这里元素是一个组件
像下面这样
const newComponent = forwardRef(({children, ...otherprops}, ref){
return (
<div {...otherprops} ref={otherprops.innerRef}>
{children}
</div>
)
})
得到
ref
是 forwardRef 中的 null
...可重现的例子:- https://codesandbox.io/s/forward-ref-cloneelement-1msjp
最佳答案
尝试将 innerRef
更改为 ref
,您添加 innerRef
属性并期望它在 ref
处有效:
import React, { useRef } from 'react';
function RefForm(props) {
const setRefs = useRef(new Map()).current;
const { children } = props;
return (
<div>
{React.Children.map(children, child => {
return React.cloneElement(child, {
// v not innerRef
ref: node => {
console.log('imHere');
return !node
? setRefs.delete(child.key)
: setRefs.set(child.key, node);
}
});
})}
</div>
);
}
export default RefForm;
然后,您可以根据需要超出 ref:
const Email = React.forwardRef((props, ref) => {
console.log('email--', ref);
ref(); // logs "imHere"
return (
<div style={{ marginTop: '30px' }}>
<label>this is email</label>
<input name="email" ref={props.innerRef} />
</div>
);
});
编辑:
对于类组件需要使用 another key then
ref
。// class component
class Name extends Component {
render() {
console.log('name--', this.props.innerRef);
return (
<div style={{ marginTop: '30px' }}>
<label>this is name</label>
<input name="name" ref={this.props.innerRef} />
</div>
);
}
}
// functional component
const Email = props => {
console.log('email--', props.innerRef);
return (
<div style={{ marginTop: '30px' }}>
<label>this is email</label>
<input name="email" ref={props.innerRef} />
</div>
);
};
// cloneElement
function RefForm(props) {
const setRefs = useRef(new Map()).current;
const { children } = props;
return (
<div>
{React.Children.map(children, child => {
return React.cloneElement(child, {
innerRef: node => {
return !node
? setRefs.delete(child.key)
: setRefs.set(child.key, node);
}
});
})}
</div>
);
}
关于javascript - 通过 cloneElement reactjs 传递 forwardRef,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58803654/