Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(筆記)React.forwardRef #136

Open
gracekrcx opened this issue Dec 14, 2022 · 0 comments
Open

(筆記)React.forwardRef #136

gracekrcx opened this issue Dec 14, 2022 · 0 comments

Comments

@gracekrcx
Copy link
Owner

gracekrcx commented Dec 14, 2022

情境:
當引用了一個共用元件
寫好 <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 會指向 DOM 節點
可以照需求寫 function 去操控 ref.current

const CustomSlick = React.forwardRef((props, ref) => (
  <Slider ref={ref} {...setting}>
    {props.children}
  </Slider>
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef();

const handleClick = ()=>{
 ref.current.stop()
}

<CustomSlick ref={ref}>
 <div onClick={handleClick}>STOP!</div>
</CustomSlick >;

console.log('ref', ref) 會是 ref {current: null} 但操控沒有問題

傳送 ref 到 DOM component

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant