[英]How to pass id from one component to another component onclick of an element
[英]how to scroll from one component to an element of another component?
我有 2 個組件,即組件 A 和組件 B,它們在同一頁面中呈現。 我需要的是在單擊組件 A 中的按鈕后滾動到組件 B 的 div。
B組份:
import React, { FC, useRef } from 'react';
const Footer: FC<Props> = ({ children }) => {
const commentSection = useRef(null);
const gotoCommentSection = () => window.scrollTo({top: commentSection.current.offsetTop, behavior: "smooth"})
return (
<>
<div className="footerClass" ref={commentSection}>
<div className="container">{children}</div>
</div>
</>
);
};
export default Footer;
如果我在組件 B 中插入此按鈕,則滾動 function 正在工作。 但是我怎樣才能從組件 A 中實現呢?
<button type="button" onClick={gotoCommentSection}>Scroll to Area</button>
我認為將 useRef 向上移動組件樹到組件 A 以及滾動 function 將起作用。 然后使用 React.forwardRef 將該引用應用於組件 B 中的元素。看起來這是一個不錯的示例: https://stackoverflow.com/a/49832065/9325243
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.