如何使用 {children} 语法将 props 从父组件(客户端)传递到子组件(服务器)?

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

我试图将属性从父组件(客户端组件)传递到子组件(服务器组件)。我正在使用

{children}
语法来渲染我的子组件。在 React 中,向子组件发送 props 就足够了
<ChildComponent someProp={someProp} />
,但是 Next.JS 不允许将服务器组件导入到客户端组件中。根据文档,如果服务器组件作为
{children}
传递,则可以在客户端组件中使用服务器组件。

我的父组件:

"use client"

import React, { useState } from "react"

const BookingsWrapper = ({ children }) => {

  const [date, setDate] = useState("");
  const [searchTerm, setSearchTerm] = useState("");

  return (
    <div className="flex">
      <div className="w-2/12 bg-gray-100 h-screen">
        <ul className="p-4">
          <li className="mb-2">
            <div className="mb-4">
              <label className="block text-gray-700 text-sm font-bold mb-2" htmlFor="date">Date:</label>
              <input
                value={date}
                onChange={(e) => {
                  setDate(e.target.value); console.log(e.target.value)}
                }
                className="appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="date" type="date" />
            </div>
          </li>
          <li className="mb-2">
            <input value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} className="appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" id="searchTerm" type="text" />
          </li>
        </ul>
      </div>
      {children}
    </div>
  )
}

export default BookingsWrapper

我想将

date
searchTerm
传递给我的子组件。

子组件如下所示:

import { authOptions } from "@app/api/auth/[...nextauth]/route";
import ReservationPreview from "@components/ReservationPreview";
import SideMenu from "@components/SideMenu";
import { getServerSession } from "next-auth";
import { redirect } from "next/navigation";

export default async function AllBookingsComponent({ date, searchTerm }) {
  const session = await getServerSession(authOptions);

  const getReservations = async () => {
    try {
      const res = await fetch("some url...", {
        headers: {
          'Authorization': 'Bearer ${session?.user?.accessToken}', 
        }
      });
  
      if (!res.ok) {
        throw new Error("Failed to fetch topics");
      }
  
      return res.json();
    } catch (error) {
      console.log("Error loading topics: ", error);
    }
  };

  const { allReservations } = await getReservations() || [];

  const filteredReservations = allReservations?.filter((r) => {
    return r.date === date;
  })

  if (!session) {
    redirect('/');
  }


  return (
    <>
      <div className="flex w-screen">
        <div className="w-10/12">
          <div className="container mx-auto my-auto px-4">
            <div className="flex flex-wrap">
              {
                date === "" ? (
                  allReservations?.map((r) => {
                    return (
                      <div hidden={!r.name.toLowerCase().includes(searchTerm.toLowerCase()) && !r.email.toLowerCase().includes(searchTerm.toLowerCase()) && (searchTerm !== "" || date !== "")} key={r._id} className="w-full md:w-1/2 lg:w-1/3">
                        <ReservationPreview reservation={r} />
                      </div>
                    )
                  })
                ) : (
                  filteredReservations?.map((r) => {
                    return (
                      <div hidden={!r.name.toLowerCase().includes(searchTerm.toLowerCase()) && !r.email.toLowerCase().includes(searchTerm.toLowerCase())} key={r._id} className="w-full md:w-1/2 lg:w-1/3">
                        <ReservationPreview reservation={r} />
                      </div>
                    )
                  })
                )
              }  
            </div>
         </div>
        </div>
      </div> 
    </>
  )
}

最后,我有一个页面将这两者结合起来......

import AllBookingsComponent from '@components/AllBookingsComponent'
import BookingsWrapper from '@components/BookingsWrapper'
import React from 'react'

const Page = () => {
  return (
    <BookingsWrapper>
      <AllBookingsComponent />
    </BookingsWrapper>
  )
}

export default Page

我尝试使用

React.cloneElement()
来实现这一点,但 Next.JS 不允许。

总而言之,我需要在子组件中访问父组件的数据,以便我可以将该数据与子组件中的数据进行比较。

谢谢!

javascript reactjs next.js react-props
1个回答
0
投票

我认为所请求的功能是不可能的,因为将动态道具传递给服务器组件听起来不太可能。 你找到解决办法了吗?

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