zoukankan      html  css  js  c++  java
  • React函数组件和Class组件使用forwardRef传递ref

    // 函数组件使用forwardRef传递ref
    const ForwardRefComponent = React.forwardRef((props, ref) => <div ref={ref.bind(this)} {...props}>子组件DOM</div>)
    
    export default function TestRef() {
      let myRef = null;
      return (
        <>
          <button onClick={() => {
            console.info(myRef);
          }}>按钮</button>
          <ForwardRefComponent ref={(r) => (myRef = r)} />
        </>  
      )
    }
    
    // Class组件使用forwardRef传递ref
    class Child extends React.Component {
      constructor(props) {
        super(props);
      }
      render() {
        return (
          <div ref={this.props.forwardedRef}>这是子组件DOM</div>
        )
      }
    }
    
    const wrapper = function (InnerComponent) {
      return React.forwardRef((props, ref) => {
        return (
          <InnerComponent forwardedRef={ref} {...props} />
        )
      })
    }
    
    const W = wrapper(Child)
    
    class Parent extends React.Component {
      constructor(props) {
        super(props);
        this.myRef = React.createRef();
      }
      render() {
        return (
          <div>
            <button onClick={() => {
              console.info(this.myRef.current);
            }}>按钮</button>
            <W ref={this.myRef} { ...this.props}/>
          </div >
        )
      }
    }
  • 相关阅读:
    浅谈分层图最短路问题
    [Luogu P2574]XOR的艺术
    luogu P2419 [USACO08JAN]牛大赛Cow Contest
    luogu P1119 灾后重建
    [国家集训队]跳跳棋
    洛谷P4147 玉蟾宫
    [ZJOI2007]棋盘制作
    树状数组模版
    Nearest Common Ancestor
    P1260 工程规划
  • 原文地址:https://www.cnblogs.com/leyi/p/14611811.html
Copyright © 2011-2022 走看看