简体   繁体   中英

Return React component as object value and bind props to it

There's one global hook which returns react components when used:

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

How do I pass props to the components I am returning from the hook?

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} />
  }
}

Passing the props down to destructed react components is a no-go for me:

const { Comp1, Comp2 } = useHook()

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

You can create the components as functional components and use useMemo inside your useHook to prevent remounting of the components on each render

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,
  }
}

The most common and elegant solution will be conditional based rendering. You can use a ternary based operator to display your component For eg.

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} /> }
        </>
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM