React Hooks实现
子调父的事件,子组件中通过props接受父组件传递过来的事件,子组件中触发时调用事件
父调子的事件,子组件中接受父组件的ref,并且通过useImperativeHandle给ref绑定事件,父组件中通过ref.current调用子组件中事件
import React, { useCallback, useRef, useImperativeHandle } from 'react'; const Child = ({ click, pRef }) => { //pRef就是父组件传过来的ref useImperativeHandle(pRef, () => ({ childClick: () => { console.log('子组件点击事件'); }, })); return <button onClick={click}>点击</button>; }; const Parent = () => { const ref = useRef(); const parentClick = useCallback(() => { console.log('父组件点击事件'); }, []); const onClick = useCallback(() => { ref.current.childClick(); }, []); return ( <div> <Child click={parentClick} pRef={ref} /> <button onClick={onClick}>点击</button> </div> ); }; export default Parent;
Vue3 Composition Api实现
子调父的事件,子组件通过defineEmits声明事件,父组件中@该事件,并赋予父组件中事件。子组件中触发时调用事件
父调子的事件,子组件通过defineExpose暴露内部事件,父组件声明ref,使用ref.value调用子组件中事件
<template> <button @click="onClick">点击</button> </template> <script setup> import { defineEmits, defineExpose } from "vue"; const emit = defineEmits(["myClick"]); const onClick = () => { emit("myClick"); }; const childClick = () => { console.log("子组件点击事件"); }; defineExpose({ childClick }); </script> <style lang="less" scoped></style>
<template> <div> <Child @myClick="parentClick" ref="cRef" /> <button @click="onClick">点击</button> </div> </template> <script setup> import { reactive, ref } from "vue"; import Child from "./Child.vue"; const cRef = ref(); const parentClick = () => { console.log("父组件点击事件"); }; const onClick = () => { cRef.value.childClick(); }; </script> <style lang="less" scoped></style>
标签:const,前端,childClick,点击,事件,互调,组件,ref From: https://www.cnblogs.com/shi2310/p/16803602.html