整理下Taro中子組件調(diào)用父組件的方法比較簡單,只要把綁定的方法傳遞進(jìn)去就好了巍杈。父組件調(diào)用的話潦俺,需要要useRef來實現(xiàn)
父組件上
import Nerv, { useState, useEffect, useRef } from "nervjs";
import BaseComponent from '@components/BaseComponent';
const Index = () => {
const refBase = useRef();
const handleBuy = (params) => {
// 購買回調(diào)
if (!refBase || !refBase.current) {
console.log(' BaseComponent RefBase undefined ');
return;
}
if (!params || !params.id || !params.dataType) {
console.log('pay params undefined', params);
return;
}
refBase.current.onCheckBuyChange(params);
}
return (
<BaseComponent refBase={refBase} >
</BaseComponent>
);
}
export default Index;
子組件上
import Nerv, { useImperativeHandle, memo, forwardRef, useState, useEffect } from "nervjs";
const BaseComponent = ({ children, refBase}) => {
const handleShowLogin = (params = true) => { // 顯示登陸
if (params) { setFromBuy(false); }
setIsOpened(params);
}
useImperativeHandle(refBase, () => ({ // 暴露方法出去
onCheckBuyChange: handleCheckBuy, // 校驗購買
onShowLogin: handleShowLogin,
onShareChange: resetShare,
}))
return (
<>
{children}
<View onClose={() => {
handleLoginClose();
}} visible={isOpened} onLoginCompelete={(res) => {
handleLoginCallBack(res)
}}
/>
</>
);
};
export default memo(forwardRef(BaseComponent));
更新 發(fā)現(xiàn)版本問題,導(dǎo)致失效了
"@tarojs/react": "3.4.1",
"@tarojs/runtime": "3.4.1",
"@tarojs/taro": "3.4.1",
"moment": "^2.29.3",
"react": "^17.0.0",
"react-dom": "^17.0.0",
"react-redux": "^7.2.0",
組件
import {useState, useEffect, useRef, useImperativeHandle, forwardRef} from 'react';
import searchEmpty from '@/assets/img/search-empty.png';
import loadingImg from '@/assets/img/loading-icon.png';
import {ScrollView, View, Image, Text} from '@tarojs/components';
import './index.scss';
const InfiniteScroll = forwardRef(({onFectch = () => {}, emptyText, renderItem}, ref) => {
const isLoad = useRef(false);
const [pageIndex, setPageIndex] = useState(1);
const [pageSize, setPageSize] = useState(10);
const [hasMore, setHasMore] = useState(true);
const [pageList, setPageList] = useState([]);
const [showEmpty, setShowEmpty] = useState(false); // 是否顯示空視圖
useEffect(() => {
onRestData();
console.log(' ==== InfiniteScroll =', ref, onFectch);
}, []);
const fetchList = async (index, size) => {
if (!hasMore) return;
isLoad.current = true;
const res = await onFectch(index, size).catch(a => a);
isLoad.current = false;
if (res?.length) {
setPageList([...pageList, ...res]);
setPageIndex(index + 1);
setHasMore(res.length >= size);
} else {
setHasMore(false);
setShowEmpty(index === 1);
}
};
const onScrollToLower = () => {
if (isLoad.current) return;
fetchList(pageIndex + 1, pageSize);
};
const onRestData = () => {
setPageIndex(1);
setPageSize(10);
setHasMore(true);
setPageList([]);
setShowEmpty(false);
fetchList(1, 10);
};
useImperativeHandle(ref, () => ({
onRestDataTest: () => {
console.log(' = onRestDataTest ');
},
}));
return (
<ScrollView className="more-list-info" scrollY scrollWithAnimation enhanced showScrollbar onScrollToLower={onScrollToLower}>
{pageList?.length > 0 && pageList.map((item, index) => renderItem(item, index, pageList.length))}
{showEmpty && (
<View className="more-list-empty">
<Image src={searchEmpty} className="more-list-empty-img" />
<View className="more-list-empty-text ">{emptyText || '暫無數(shù)據(jù)'}</View>
</View>
)}
{!showEmpty &&
(hasMore ? (
<View>
<View className="loading">
<Image src={loadingImg} alt="" className="loading-img" />
<Text className="tip">{emptyText || '正在努力加載中'}</Text>
</View>
</View>
) : (
<View>
<View className="loading">
<Text className="tip">{'沒有更多了~'}</Text>
</View>
</View>
))}
</ScrollView>
);
});
export default InfiniteScroll;
父組件
import React, {useState, useRef} from 'react';
import {View} from '@tarojs/components';
import Taro, {useRouter, useShareAppMessage} from '@tarojs/taro';
import {defaultShare} from '@/utils';
import {ProductCardRow, InfiniteScroll, CustomHeader} from '@/components';
import SortInfo from '../../components/Sort';
import HeadInfo from '../../components/Head';
import {sortGoods, sortBook} from '../../components/config';
import {getSpuListByKey} from '@/api/search';
import './index.scss';
const GoodsList = ({}) => {
const scrollRef = useRef();
const router = useRouter();
const goodsText = 'goods';
const {type, text} = router.params;
const [currIndex, setCurrIndex] = useState(0);
const [sortList, setSortList] = useState(type === goodsText ? [...sortGoods] : [...sortBook]);
const onSortChange = e => {
setCurrIndex(e, a => {
console.log(' == ', a);
});
// setTimeout(() => {
// refBase.current.onRestData();
// }, 1000);
console.log(' === remindRef ==', scrollRef);
};
const onFectch = async (index, size) => {
const res = await getSpuListByKey({
keyword: decodeURI(text),
searchSpuNewCategory: type === goodsText ? 2 : 1,
spuSortType: sortList[currIndex].id,
pageNum: index,
pageSize: size,
});
try {
return res.context.content;
} catch (error) {
return [];
}
};
useShareAppMessage(() => {
return defaultShare();
});
return (
<View className="goods-list-content">
<CustomHeader customContent>
<HeadInfo type={type === goodsText ? '商品' : '圖書'} text={decodeURIComponent(text)} />
</CustomHeader>
<SortInfo sort={sortList} currIndex={currIndex} onSortChange={onSortChange} sortId="list-sort" />
<View className="goods-list-scroll">
<InfiniteScroll ref={scrollRef} onFectch={onFectch} renderItem={(item, index) => <ProductCardRow type={type} data={item.goodsCustomVo} data-index={index} data-item={item} />} />
</View>
</View>
);
};
export default GoodsList;