整理下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));
网友评论