react获取children的ref

作为容器组件,接收来自props中的children并进行布局分配是常规需求,但如何获取children的ref呢。
其实可以使用React.cloneElement()来实现该需求, 这里以单节点为例:

const child = React.Children.only(this.props.children);

const newChild = React.cloneElement(child, {
	className: classNames(
		'new-child',
		child.props.className,
		this.props.className
	),
	ref: node = this.cnode = node,
});

return (
	<div>
		{newChild}
	</div>
)

通过cloneElement 便获取到了 children的ref this.cnode

猜你喜欢

转载自blog.csdn.net/u010464354/article/details/106135927