react,如何实现从不相关组件里调用某个指定的函数?

在使用的react版本如下:

img


A和B是两个不相关的组件,两者既不是父子,也不是兄弟,也没有共同的父组件
组件A的代码:

import React from 'react'
// import { handleFavorite } from '../../HouseDetail/index'
const Favorite = () => {
  const deleteFavorite = (e) => {
    e.stopPropagation()
    let index = e.target.getAttribute("data-index")
    // handleFavorite()
  }
return (
   <span className={styles.delete} data-index={index} onClick={deleteFavorite}>
      <CloseCircleOutline />
   span>
)
}

组件B的代码:

import React from 'react'
function HouseDetail() {
  const [isfavorite, setIsfavorite] = useState(false)
  function handleFavorite() {
    if (isfavorite) {
      API.delete(`/user/favorites/${id}`).then(res=>{
      setIsfavorite(false)
    })
  }
return (
// ...
)
}

请问如何才能让B组件里的handleFavorite函数放到A组件里使用,并实现点击A组件里的span即可实现删除功能?请在现有代码基础上展示代码举例说明,谢谢。

组件之间不相关,那肯定是没法调用的,你能确保组件B提前于A组件加载完成吗。

最合理的应该公用逻辑抽离,然后在需要的地方引入。