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

  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章