對于我在 React 應用程式中創建的 (onClick) 處理程式函式下方的“后退”按鈕。
const { length: historyLength, goBack, replace } = useHistory();
const handleBack = () => {
if (historyLength > 2) {
goBack();
} else {
// History length is 2 by default when nothing is pushed to history yet
// https://stackoverflow.com/questions/9564041/why-history-length-is-2-for-the-first-page
replace(HomePage);
}
};
然后我將 onClick 處理程式傳遞給我的子組件,例如:<Button onClick={handleBack}/>
我handleBack在我的 React 應用程式的多個地方使用這個功能。它是一個好的方法,例如一個輔助函式,以及如何準確?
uj5u.com熱心網友回復:
我也沒有看到代碼有任何問題或將其用作實用程式回呼。
它是一個好的方法,例如一個輔助函式,以及如何準確?
任何時候你可以讓你的代碼更干燥(不要重復你自己)這通常是一件好事。我個人的經驗法則是,如果我第三次撰寫相同的實用程式代碼,我會花一些時間將其重構為一個通用實用程式(和單元測驗!!)。
我可能會建議創建一個自定義掛鉤來回傳后處理程式。
例子:
import { useHistory } from 'react-router-dom';
const useBackHandler = () => {
const history = useHistory();
const handleBack = React.useCallback(() => {
const { length: historyLength, goBack, replace } = history;
if (historyLength > 2) {
goBack();
} else {
replace(HomePage);
}
}, []);
return handleBack;
};
export default useBackHandler;
現在你有一個單獨的鉤子可以匯入和使用。
import useBackHandler from '../path/to/useBackHandler';
...
const backHandler = useBackHandler();
...
<button type="button" onClick={backHandler}>Back?</button>
如果您在較舊的類組件中需要此功能,那么您將需要一種將其handleBack作為道具注入的方法。為此,您可以創建一個高階組件。
例子:
import useBackHandler from '../path/to/useBackHandler';
const withBackHandler = Component => props => {
const backHandler = useBackHandler();
return <Component {...props} backHandler={backHandler} />;
};
export default withBackHandler;
要使用、匯入withBackHandler和裝飾 React 組件并訪問props.backHandler.
import withBackHandler from '../path/to/withBackHandler';
class MyComponent extends React.Component {
...
someFunction = () => {
...
this.props.backHandler();
}
...
}
export default withBackHandler(MyComponent);
uj5u.com熱心網友回復:
@meez
不明白為什么這不起作用。只是幾件事:(a)我會e.preventDefault()在函式中添加事件引數和(b)會小心你在onClick按鈕屬性上傳遞的函式名:handleBackClick !== handleBack,你會得到一個 ReferenceError 因為未定義的函式。
此外,我還注意到這可以通過本機瀏覽器功能來實作。這是一個片段:
const { length: historyLength, back } = window.history;
const { replace } = window.location;
const handleBack = (e) => {
e.preventDefault();
if (historyLength > 2) {
back();
} else {
replace('homepageUrl');
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/474877.html
上一篇:無法將'LinkedList::filter(void(*)(Node*))::<lambda(Node*)>'轉換為'void(*)(Node*)'
下一篇:訪問指向成員函式的指標陣列的元素
