Taro+TypeScript实现任意页面点击回到首页顶部
思路:存一个变量到本地,到达首页的时候查看是否有这个变量,在再次回到首页时检查是否存在这个变量,要是有则利用Taro的回到顶部api。 任意页面的点击回到首页位置:
<View className='item' onClick={() => goToCard()}> <Image className='mingpian_icon' src={mingpian} /> <Text className='contact'>名片</Text> </View> 复制代码
import { storage } from '@utils'; const goToCard = () => { storage.setLocalStorage('isTop', true); gotoSwitch(`/pages/home/home`); setSelectedIndex(0); }; 复制代码
首页的回到顶部操作:(回到顶部之后记得清除)
import { storage } from '@utils'; useDidShow(() => { const isTop = storage.getLocalStorage('isTop'); if (isTop) { scrollTop(); storage.removeLocalStorage('isTop'); } }); 复制代码
//storage.ts对Taro的原有寸本地api进行二次封装 import Taro from '@tarojs/taro'; // 获取 LocalStorage const getLocalStorage = (name) => { try { const value = Taro.getStorageSync(name); return value; } catch (e) { // error } }; // 设置 LocalStorage const setLocalStorage = (name, value) => { try { Taro.setStorageSync(name, value); } catch (e) { // error } }; // 删除 LocalStorage const removeLocalStorage = (name) => { try { Taro.removeStorageSync(name); } catch (e) { // error } }; // 清空本地缓存 const clearLocalStorage = () => { Taro.clearStorage(); }; export default { getLocalStorage, setLocalStorage, removeLocalStorage, clearLocalStorage, }; 复制代码
//utils里的index.ts export { default as storage } from './storage';
作者:廖锦玉
链接:https://juejin.cn/post/7038193201861279751
伪原创工具 SEO网站优化 https://www.237it.com/