美文网首页
Taro中使用React父组件调用子组件

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

作者: RadishHuang | 来源:发表于2021-09-07 15:04 被阅读0次

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

    相关文章

      网友评论

          本文标题:Taro中使用React父组件调用子组件

          本文链接:https://www.haomeiwen.com/subject/jkqpwltx.html