Taro中使用React父组件调用子组件

整理下Taro中子组件调用父组件的方法比较简单,只要把绑定的方法传递进去就好了。父组件调用的话,需要要useRef来实现

父组件上
import Nerv, { useState, useEffect, useRef } from "nervjs";
import BaseComponent from '@components/BaseComponent';


const Index = () => {
  const refBase = useRef();

  const handleBuy = (params) => {
    // 购买回调
    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 (
    
    
  );
}

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}
       {
          handleLoginClose();
        }} visible={isOpened} onLoginCompelete={(res) => {
          handleLoginCallBack(res)
        }}
      />
    
  );
};
export default memo(forwardRef(BaseComponent));


更新 发现版本问题,导致失效了

 "@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 (
    
      {pageList?.length > 0 && pageList.map((item, index) => renderItem(item, index, pageList.length))}
      {showEmpty && (
        
          
          {emptyText || '暂无数据'}
        
      )}

      {!showEmpty &&
        (hasMore ? (
          
            
              
              {emptyText || '正在努力加载中'}
            
          
        ) : (
          
            
              {'没有更多了~'}
            
          
        ))}
    
  );
});

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 (
    
      
        
      
      
      
         } />
      
    
  );
};

export default GoodsList;

你可能感兴趣的:(Taro中使用React父组件调用子组件)