ref可以获取dom节点或者react元素的实例,一般有三种使用方法
1. string ref

使用方法就是在react元素上使用一个ref属性,然后传入一个字符串,最后react在完成这个节点的渲染之后,就会在this.ref这个对象上增加一个这个字符串的key,这个key对应的value就是这个react元素的实例。如果是一个function component则会报错。如果要对function component使用ref,就必须把function component用forwardRef给包起来

2. function

3. createRef

createRef会创建一个对象,这个对象默认值是
{current: null}
,把这个this.objRef放到ref属性里后,这个节点对应的实例就会挂载到这个对象的current上。
网友评论