[英]How to use ref from parent component in react
我有一個功能組件(父)和一個 class 組件(子)。 我的問題是我無法將父級的重定向鏈接重定向到子級的特定部分。
我在下面有這個 function,它在子組件中工作正常,但在父組件中引用未知。
handleOnClick = (event) => {
//.current is verification that element has rendered
if (this.filmsContent.current) {
this.filmsContent.current.scrollIntoView({
behavior: "smooth",
block: "nearest",
});
}
};
以及對目標的引用:
<div ref={this.filmsContent} ></div>
我想在帶有 onClick 的父組件中使用這個 function 但是子組件的引用this.filmsContent
我不知道該怎么做。 你知道如何解決它嗎?
你可以
import { useHistory } from 'react-router-dom';
在您的導出默認值之后...
const history = useHistory();
在您的句柄 function 中使用:
history.push('/path');
您可以在接收 function 作為參數的父級中創建一個 function 並將其像道具一樣發送給子級,如下所示:
function Child(){
const [fun, setFun] = useState(null);
const parentFunction = (childFunction) =>{
setFun(childFunction);
}
}
然后你像這樣把它發送給孩子:
<Child parentFunction={parentFunction}/>
現在,當您渲染孩子時,在 ComponentDidMount function 中您可以這樣做:
class Child extends React.Component{
componentDidMount(){
this.props.parentFunction(handleOnClick);
}
}
這樣做,您將設置變量 fun 等於您孩子中的 function ,當您想在父組件中使用它時,您只需調用fun()
,例如:
<button onClick={fun}/>
或者
const doSomething = () =>{
fun();
}
希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.