Next.js 如何将 'setSomeState' 传递给孩子

问题描述 投票:0回答:1

我正在尝试构建一个带有聊天块的应用程序,该聊天块不会在页面更改时刷新。子页面包含提示,使用户无需键入常见响应。我的所有页面都位于 /board 目录中,该目录有一个名为“BoardContainer,tsx”的顶级页面:

'use client'
import React, { ReactElement, ReactNode } from 'react';
import { useState } from 'react';
import { usePathname } from 'next/navigation';
import ChatBlock from '../components/ChatBlock/ChatBlock';
import AboutPage from '../dashboard/about/background/page';

interface BoardContainerProps {
  children: ReactNode;
}

const BoardContainer: React.FC<BoardContainerProps> = ({ children }) => {
  const [selectedPrompt, setSelectedPrompt] = useState('');
  const pathname = usePathname();

  const sendPrompt = (prompt: string) => {
    setSelectedPrompt(prompt);
  }

  const childrenWithProps = React.Children.map(children, child => {
    console.dir(child);
    if (React.isValidElement(child)) {
      return React.cloneElement(child as ReactElement<any>, { sendPrompt });
    }
    console.dir(child);
    return child;
  });

  console.dir(pathname);

  return (
    <>
      <>
        { pathname === '/board/about' ?  <AboutPage sendPrompt={sendPrompt} /> : <PageContent /> }
        {/* This works but not suitable for more than 2 child pages */}

        {/* childrenWithProps */}
        {/* this doesn't work either */}

        {/* children */}
      <>

      <>
        <ChatBlock
          prompt={selectedPrompt}
        />
      </>
    </>
  )
}

export default BoardContainer;

我想出了一个使用 usePathname 的解决方法,本质上是对子值进行硬编码并传递 sendPrompt 函数,但这很麻烦。 我尝试使用 React.cloneElement,但我要么使用不正确,要么误解了某些内容。如何通过 {children} 传递 sendPrompt 函数?

reactjs next.js
1个回答
0
投票

您将使用回调函数...

<ChatBlock prompt={selectedPrompt} setSelectedPrompt={setSelectedPrompt} />
然后对于聊天块组件本身的 prop...
setSelectedPrompt: React.Dispatch<React.SetStateAction<string>>;
然后对于您在聊天块代码中使用它的地方......
onClick={() => setSelectedPrompt('prompt1')}

© www.soinside.com 2019 - 2024. All rights reserved.