gracekrcx / weekly-notes

4 stars 0 forks source link

(筆記)React.forwardRef #136

Open gracekrcx opened 1 year ago

gracekrcx commented 1 year ago

情境: 當引用了一個共用元件 寫好 <Common>{......children}</Common> 當 children 裡的 event 要去控制 <Common> 這個元素

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;

好消息,現在 ref.current 會指向