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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值