验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

ForwardRef useImperativeHandle方法怎么使用

阅读:1121 来源:乙速云 作者:代码code

ForwardRef useImperativeHandle方法怎么使用

一、获取Ref的方式

  • 使用字符串

  • 使用函数

  • 使用Ref对象(最常见)

  • 使用createRef

export class RefTest extends React.Component {
    currentDom: React.RefObject = React.createRef();
    currentChildren: React.LegacyRef = React.createRef();
    render() {
        console.log(this.currentChildren, this.currentDom);
    return (
        <>
            你好
                             )     } }

ForwardRef useImperativeHandle方法怎么使用

  • 使用useRef

export const RefTest = () => {
    const currentDom = useRef(null);
    const currentChildren = useRef(null);
    useEffect(() => {
        console.log(currentChildren, currentDom, '这里也可以打印出来了');
     },[])
   return (
   <>
       你好
                ) }

二、Ref实现组件通信

来个极简版

ForwardRef useImperativeHandle方法怎么使用

import React, { useEffect } from 'react';
class Son extends React.Component{
    state={
        sonValue:''
    }
    render(){
    return 
        
子组件的信息: {this.state.sonValue}
        
对父组件说
        this.props.setFather(e.target.value)}/>         
    } } export default function Father(){ const [ fatherValue , setFatherValue ] = React.useState('') const sonRef = React.useRef(null) return 
    
父组件的信息: {fatherValue}
    
对子组件说
     sonRef.current.setState( {sonValue: e.target.value})}/>          
}

ForwardRef useImperativeHandle方法怎么使用

三、ForwardRef

比如跨层级获取ref信息

ForwardRef useImperativeHandle方法怎么使用

![图片转存失败,建议将图片保存下来直接上传
        import React from 'react';
interface IProps {
    targetRef: React.RefObject
    otherProps: string
}
interface IGrandParentProps {
    otherProps: string
}
class Son extends React.Component {
    constructor(props) {
        super(props);
        console.log(props,'son中的props');
     }
     render() {
         // 最终目标是获取该DOM元素的信息
         return 真正目的是这个
     }
}
class Farther extends React.Component {
    constructor(props) {
        super(props)
        console.log(props, 'father中的props');
    }
    render() {
        return (
        // 继续将ref传给Son
            
         )
    }
}
// 在这里使用了forwardRef, 相当于把传入的ref转发给Father组件
const ForwardRef = React.forwardRef((props: IGrandParentProps, ref: React.RefObject) 
    => )

 image.png(https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/5d49e7ff4ec940b28dcb3a780fd5c0a7~tplv-k3u1fbpfcp-watermark.image?)
export class GrandFather extends React.Component {
    currentRef:React.RefObject = React.createRef();
    componentDidMount() {
        // 获取到的Ref信息
        console.log(this.currentRef, 'componentDidMount');
    }
    render() {
        return (
        
        )
    }
}
]()

ForwardRef useImperativeHandle方法怎么使用

四、 useImperativeHandle

看完参数其实就能够清楚地知道它的作用了,可以通过forwardRef+useImperativeHandle自定义获取到的ref信息

再来两个简单例子:

import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react"
const ForwardItem = forwardRef((props, ref) => {
    const [sonValue, setSonValue] = useState('修改之前的值');
    useImperativeHandle(ref, () => ({
        setSonValue,
    }))
    return (
        
子组件的值: {sonValue}
    ) }) export const Father = () => {     const testRef = useRef(null);     useEffect(() => {         console.log(testRef.current, 'ref获取到的信息')      })     const changeValue = () => {         const DURATION = 2000;         setTimeout(() => {         testRef.current.setSonValue('我已经修改值啦')         },DURATION)     }     return (     <>                 changeValue()}>2s后修改子组件ForwardItem的值          ) }
const ForwardItem = forwardRef((props, ref) => {
    const elementRef: RefObject = useRef();
    useImperativeHandle(ref, () => ({
        elementRef,
    }))
    return (
        我是一个子组件
     )
})
export const Father = () => {
    const testRef = useRef(null);
    useEffect(() => {
        console.log(testRef.current, 'ref获取到的信息')
     })
    return (
    <>
        
    
    )
}

ForwardRef useImperativeHandle方法怎么使用

分享到:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
相关文章
{{ v.title }}
{{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
你可能感兴趣
推荐阅读 更多>