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 >
    )
  }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM