zoukankan      html  css  js  c++  java
  • React 函数组件传递ref

    以前理所当然的认为,只要ref作为props传进去,就可以直接给某个子组件用了,但是实际上不是这样的

    const Test = ({ref}) => {
        return <div ref={ref}>
            <p>hahahha</p>
        </div>
    }
    
    class TestWarper extends React.Component {
        ref = React.createRef();
        render() {
            return <Test ref={this.ref} />
        }
    }
    // 上面这种情况下,this.ref永远是{current: null},在Test子组件也发现,传进来的ref是undefined

    面对这种情况,React有个方法,可以支持Ref的传递:forwardRef

    import React, {forwardRef} from 'react';
    
    // 包一层forwardRef
    const Test = forwardRef((props, ref:any) => {
        return <div ref={ref}>
            <p>hahahha</p>
        </div>
    })
    
    class TestWarper extends React.Component {
        ref = React.createRef();
        render() {
            return <Test ref={this.ref} />
        }
    }
    // 这种情况下,this.ref就会是{current: div}了
  • 相关阅读:
    js 平坦化控制流
    js变量名混淆
    ERR_CERT_INVALID
    ERR_CERT_AUTHORITY_INVALID
    @babel/preset-env
    @babel/plugin-transform-runtime
    terminal
    @babel/plugin-proposal-class-properties
    Zotero
    随记 日后整理
  • 原文地址:https://www.cnblogs.com/amiezhang/p/13174745.html
Copyright © 2011-2022 走看看