互相调用方法
1、react18.3 互相调用方法
- 2-1、子组件调用父组件方法
Father.tsx
jsimport Son from './Son' export default function Father() { const handleMessageFromChild = (message) => { console.log(message) } return ( <> father <Son sendMessage={handleMessageFromChild} /> </> ) }
Son.tsx
jsexport default function Son({ sendMessage }) { const handleClick = () => { sendMessage('Hello from Child!') // 调用父组件的函数并传递消息 } return ( <> <div> <button onClick={handleClick}>发送消息给父组件</button> </div> </> ) }
- 2-2、父组件调用子组件方法
Father.tsx
tsximport Son from './Son' import { useRef } from 'react' export default function Father() { const sonRef = useRef(null) const fatherFun = () => { if (sonRef.current) { sonRef.current.sonFun() } } return ( <> father <Son myRef={sonRef}/> <button onClick={fatherFun}>父组件调用子组件</button> </> ) }
Son.tsx
tsximport { useImperativeHandle } from 'react' export default function Son(props) { useImperativeHandle(props.myRef, () => ({ sonFun })) const sonFun = () => { console.log('子组件的方法被调用了!') // 调用父组件的函数并传递消息 } return ( <> <div> <span>子组件</span> </div> </> ) }
2、小程序 互相调用方法
- 2-1、子组件调用父组件方法
Father
html<text>Father</text> <Son bind:fatherFun="fatherFun"/>
jsComponent({ methods: { fatherFun(e){ console.log('fatherFun被执行了==>',e.detail)//获取子组件的值 }, } })
Son
html<text>Son</text> <button bindtap="sonFun">调用父组件方法</button>
jsComponent({ methods: { sonFun(){ console.log('dd') this.triggerEvent('fatherFun','传给父组件的值') }, } })
- 2-2、父组件调用子组件方法
Father
html<text>Father</text> <Son id="son"/> <button bind:tap="fatherFun">调用子组件方法</button>
jsComponent({ methods: { fatherFun(e){ this.son = this.selectComponent('#son'); if (this.son) { // 调用子组件的方法 this.son.sonFun(); } }, } })
son
jsComponent({ methods: { sonFun(){ console.log('子组件方法执行了') }, } })
3、vue3.5 互相调用方法
2-1、子组件调用父组件方法
Father.vue
vue<script setup lang="ts"> import Son from './Son.vue' function fatherFun(e) { console.log('父类方法被执行了==》' + e) } </script> <template> <div> Father <Son @fatherFun="fatherFun"/> </div> </template> <style scoped> </style>
Son.vue
vue<script setup lang="ts"> import { defineEmits, ref } from 'vue' const emit = defineEmits(['fatherFun']) function sonFun() { emit('fatherFun', '子组件的值') } </script> <template> <div> <button @click="sonFun">子组件</button> </div> </template> <style scoped> </style>
2-2、父组件调用子组件方法
Father.vue
vue<script setup lang="ts"> import { ref } from 'vue' import Son from './Son.vue' const son = ref(null) function fatherFun() { if (son.value) { son.value.sonFun() } } </script> <template> <div> <button @click="fatherFun">调用子组件方法</button> <Son ref="son"/> </div> </template> <style scoped> </style>
Son.vue
vue<script setup lang="ts"> import { defineExpose } from 'vue' defineExpose({ sonFun }) function sonFun() { console.log('子组件的方法') } </script> <template> <div> <div>子组件</div> </div> </template> <style scoped> </style>