Nextjs -如何传递组件作为 prop ?

5anewei6  于 2023-01-20  发布在  其他
关注(0)|答案(2)|浏览(198)

我正试图弄清楚如何传递一些组件作为 prop ,然后使用它们。我有这个工作在一个文件中,但想把它分解成一个可重用的组件。
这是一个页面我有:career.tsx

export function Full() {
   return ( <Text>Full</Text> );
}

export function Condensed() {
   return ( <Text>Condensed</Text> );
}

export function Video() {
   return ( <Text>Video</Text> );
}

export default function Career() {
   const [activeComponent, setActiveComponent] = useState(null);
   
   return (
      <>
         <Title>Career</Title>

         {/* Passing components as props */ }
         <ModuleToggle_withState video={<Video/>} condensed={<Condensed/>} full={<Full/>}
               setActiveComponent={setActiveComponent} />

         { activeComponent }
      </>
   );
}

模块切换状态.tsx

export function ModuleToggle_withState({Video, Condensed, Full}:any, setActiveComponent:any) {
// Will research typescript types and update the "any"

   // Trying to figure out how to pass and use Components which were passed
   useEffect(() => {
      switch(section) {
         case 'video':
            setActiveComponent=<Video/>
         case 'condensed':
            setActiveComponent=<Condensed/>
         case 'full':
            setActiveComponent=<Full/>
      }
   }, [section]);

   return (
      ...
   );
}
9avjhtql

9avjhtql1#

最好有条件地呈现内容。

export function ModuleToggle_withState({ activeComponent }) {   
  return (
    <>
      {activeComponent === "video" && <Video/>}
      {activeComponent === "condensed" && <Condensed/>}
      {activeComponent === "full" && <Full/>}
    </>
  );
}

使用它:

export default function Career() {
  const [activeComponent, setActiveComponent] = useState("video");
  return (
    <>
      <Title>Career</Title>
      <ModuleToggle_withState activeComponent={activeComponent} />
    </>
  )
}
laik7k3q

laik7k3q2#

你必须创建一个布局:

export default function Career({children }) {
   // remove the state
   // use router for active something...
   const router = useRouter();
   // with param send how component you need active, with onCLick or link
   return (
      <div onClick={() => router.push("/yourpath?activeComponent=video">
         <Title>Career</Title>
         { children }
      <div/>
   );
}

另一个组成部分:

export default function ModuleToggleWithState() {
  const router = useRuter();
  const section = router.query.activeComponent
   useEffect(() => {
      switch(section) {
         case 'video':
            setActiveComponent=<Video/>
         case 'condensed':
            setActiveComponent=<Condensed/>
         case 'full':
            setActiveComponent=<Full/>
      }
   }, [section]);

   return (
      <Career>
        \\ everything you want to show here !!
     </Career>
   );
}

相关问题