Taro中使用React父組件調(diào)用子組件

整理下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;

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末烘贴,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子撮胧,更是在濱河造成了極大的恐慌桨踪,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,427評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件趴樱,死亡現(xiàn)場離奇詭異馒闷,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)叁征,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,551評論 3 395
  • 文/潘曉璐 我一進(jìn)店門纳账,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人捺疼,你說我怎么就攤上這事疏虫。” “怎么了啤呼?”我有些...
    開封第一講書人閱讀 165,747評論 0 356
  • 文/不壞的土叔 我叫張陵卧秘,是天一觀的道長。 經(jīng)常有香客問我官扣,道長翅敌,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,939評論 1 295
  • 正文 為了忘掉前任惕蹄,我火速辦了婚禮蚯涮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘卖陵。我一直安慰自己遭顶,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,955評論 6 392
  • 文/花漫 我一把揭開白布泪蔫。 她就那樣靜靜地躺著棒旗,像睡著了一般。 火紅的嫁衣襯著肌膚如雪撩荣。 梳的紋絲不亂的頭發(fā)上铣揉,一...
    開封第一講書人閱讀 51,737評論 1 305
  • 那天饶深,我揣著相機(jī)與錄音,去河邊找鬼逛拱。 笑死粥喜,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的橘券。 我是一名探鬼主播,決...
    沈念sama閱讀 40,448評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼卿吐,長吁一口氣:“原來是場噩夢啊……” “哼旁舰!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起嗡官,我...
    開封第一講書人閱讀 39,352評論 0 276
  • 序言:老撾萬榮一對情侶失蹤箭窜,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后衍腥,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體磺樱,經(jīng)...
    沈念sama閱讀 45,834評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,992評論 3 338
  • 正文 我和宋清朗相戀三年婆咸,在試婚紗的時候發(fā)現(xiàn)自己被綠了竹捉。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,133評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡尚骄,死狀恐怖块差,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情倔丈,我是刑警寧澤憨闰,帶...
    沈念sama閱讀 35,815評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站需五,受9級特大地震影響鹉动,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜宏邮,卻給世界環(huán)境...
    茶點故事閱讀 41,477評論 3 331
  • 文/蒙蒙 一泽示、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧蜀铲,春花似錦边琉、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,022評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至厌丑,卻和暖如春定欧,著一層夾襖步出監(jiān)牢的瞬間渔呵,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,147評論 1 272
  • 我被黑心中介騙來泰國打工砍鸠, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留扩氢,地道東北人。 一個月前我還...
    沈念sama閱讀 48,398評論 3 373
  • 正文 我出身青樓爷辱,卻偏偏與公主長得像录豺,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子饭弓,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,077評論 2 355

推薦閱讀更多精彩內(nèi)容