簡體   English   中英

將 React 組件返回為 object 值並將道具綁定到它

[英]Return React component as object value and bind props to it

有一個全局鈎子在使用時會返回反應組件:

const { SomeComponent1, SomeComponent2 } = useHook({ prop1, prop2 })

如何將道具傳遞給從鈎子返回的組件?

const useHook = ({ prop1, prop2 }) => {

  return {
    SomeComponent1, // <-- I'd like to 'bind' props to the component here
    SomeComponent2,
    // THE CODE BELOW IS INCORRECT
    // it's a way to illustrate what I am after:
    // SomeComponent1: <SomeComponent1 prop1={prop1} />
  }
}

將道具傳遞給被破壞的反應組件對我來說是不行的:

const { Comp1, Comp2 } = useHook()

return (
  <Comp1 prop={prop1} />
)

您可以將組件創建為功能組件並在 useHook 中使用useMemo以防止在每次渲染時重新安裝組件

const useHook = ({ prop1, prop2 }) => {

  const SomeComponent1Wrap = useMemo(() => ( ) => {
     return <SomeComponent1 prop={prop1} />
  }, [props1]);

  const SomeComponent2Wrap = useMemo(() => ( ) => {
     return <SomeComponent2 prop={prop2} />
  }, [props2]);

  return {
    SomeComponent1: SomeComponent1Wrap, 
    SomeComponent2: SomeComponent2Wrap,
  }
}

最常見和最優雅的解決方案將是基於條件的渲染。 您可以使用基於三元的運算符來顯示您的組件例如。

import React,{useState} from "react";
import {Comp1} from "./comp1"; 
import {Comp2} from "./comp2"; 
function Test(){
    const [display,setDisplay] = useState(true);
    render(){
        <>
            {display ? <Comp1 props={props} /> : <Comp2 props={props} /> }
        </>
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM