【问题标题】:What is the alternative to return component from react custom hook?从反应自定义钩子返回组件的替代方法是什么?
【发布时间】:2022-06-10 21:45:45
【问题描述】:

我遇到了需要从自定义钩子返回 2 个反应组件的情况。只是简单地给你一个概述,我有一个自定义的钩子,所有必需的状态都聚集在一起。在自定义钩子中,我还将 2 个组件存储在变量中,并传递从另一个自定义钩子返回的道具。我在自定义钩子中返回 2 个组件。一些开发人员说在自定义钩子中返回反应组件是不好的。所以我正在寻找替代方案。这是代码演示。

import FirtComponent from '/'
import SecondComponent from "/"

const useCustomHook =()=> {
  
 const {props} =usePropsHook()
  
const {firstComponentProps,secondComponentProps} =props

 return {firstComponent :<FirstComponent {...firstComponentProps}>,secondComponent :<SecondComponent {...secondCOmponentProps} />} 
 
 
}

我这样做是为了可以灵活地在任何我想要的地方显示这两个组件。例如彼此相邻,第一个组件在顶部,第二个组件在下面。 FirstComponent 在其他模态和类似的东西旁边。

【问题讨论】:

  • 你能解释一下你想要达到什么目标吗?
  • 我有一个自定义钩子,它返回 2 个反应组件。这样组件就可以在我调用自定义钩子的任何地方显示。它工作正常,我可以实现我想要的。但是,我听说在自定义钩子中返回反应组件不是一个好习惯。所以,我正在寻找一种替代方法,它可以以相同的方式工作,而无需在自定义钩子中返回组件。

标签: reactjs react-hooks react-custom-hooks


【解决方案1】:

你为什么不直接创建一个新的组件,然后根据一个道具来渲染 Component1 或 Component2?

import FirstComponent from '/'
import SecondComponent from "/"

const MyComponent = ({myCustomProp}) => {
  
    const { props } = usePropsHook()

    const { firstComponentProps, secondComponentProps } =props

    if (myCustomProp) return <FirstComponent {...firstComponentProps} />

    return <SecondComponent {...secondComponentProps} />
}

那么你就可以像这样使用这个组件了

<MyComponent myCustomProp />    // render FirstComponent
<MyComponent />                 // render SecondComponent

【讨论】:

    猜你喜欢
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 2022-07-18
    • 2020-03-08
    相关资源
    最近更新 更多