ref用法

 

目录

React中提供两种方法创建ref对象:

类组件获取 Ref 三种方式

① Ref属性是一个字符串。

② Ref 属性是一个函数。

③ Ref属性是一个ref对象。

高级用法1:forwardRef 转发 Ref

高级用法2:ref实现组件通信


【ref作用】:最熟悉的就是  用 Ref 获取真实 DOM 元素和获取类组件实例,除此之外的功能,ref 派生出一些其他的高级用法,能够解决一些特殊场景下的问题

React中提供两种方法创建ref对象:

        第一种: 类组件中  React.createRef 创建一个 ref 对象。

class Index extends React.Component{
    constructor(props){
       super(props)
       this.currentDom = React.createRef(null)
    }
    componentDidMount(){
        console.log(this.currentDom)
    }
    render= () => 
ref对象模式获取元素或组件
}

        第二种:函数组件中  React.useRef 创建 Ref

export default function Index(){
    const currentDom = React.useRef(null)

    React.useEffect(()=>{
        console.log( currentDom.current ) // div
    },[])

    return  
ref对象模式获取元素或组件
}

【什么是 ref 对象,所谓 ref 对象就是用 createRef 或者 useRef 创建出来的对象】

【问:在函数组件中为什么不能用 createRef ?】
        答:类组件有一个实例 instance 能够维护像 ref 这种信息,但函数组件每次更新时所有的变量都会重新声明,此时 ref 就会随着函数组件执行被重置。


类组件获取 Ref 三种方式

  • ① Ref属性是一个字符串。
/* 类组件 */
class Children extends Component{  
    render=()=>
hello,world
} /* TODO: Ref属性是一个字符串 */ export default class Index extends React.Component{ componentDidMount(){ console.log(this.refs) } render=()=>
字符串模式获取元素或组件
}

React 在底层逻辑,会判断类型,如果是 DOM 元素,会把真实 DOM 绑定在组件 this.refs (组件实例下的 refs )属性上,如果是类组件,会把子组件的实例绑定在 this.refs 上。(函数组件没有实例,不能被 Ref 标记)

  • ② Ref 属性是一个函数。
class Children extends React.Component{  
    render=()=>
hello,world
} /* TODO: Ref属性是一个函数 */ export default class Index extends React.Component{ currentDom = null currentComponentInstance = null componentDidMount(){ console.log(this.currentDom) console.log(this.currentComponentInstance) } render=()=>
this.currentDom = node } >Ref模式获取元素或组件
this.currentComponentInstance = node } />
}

  • ③ Ref属性是一个ref对象。
class Children extends React.Component{  
    render=()=>
hello,world
} export default class Index extends React.Component{ currentDom = React.createRef(null) currentComponentInstance = React.createRef(null) componentDidMount(){ console.log(this.currentDom) console.log(this.currentComponentInstance) } render=()=>
Ref对象模式获取元素或组件
}

高级用法1:forwardRef 转发 Ref

高级用法2:ref实现组件通信

你可能感兴趣的:(react之函数组件,类组件,react.js,前端,前端框架)