我想将此函数导入到我的主 tsx 文件中:
"use client"
// components/LoadMore
import { useState } from 'react';
export function useLoadMore() {
const [postNum, setPostNum] = useState(3);
const handleClick = () => {
setPostNum(prevPostnum => prevPostnum + 3)
}
return {
postNum, handleClick
};
}
当我尝试在主文件中使用例如
const {postNum, handleClick} = useLoadMore()
来调用它时(这是我导入它的方式import { useLoadMore } from '../app/components/LoadMore'
),以下错误作为输出返回:Error: (0 , _app_components_LoadMore__WEBPACK_IMPORTED_MODULE_4__.useLoadMore) is not a function
我打算使用 main.tsx 文件中的函数,如下所示:
export default function Home() {
const posts = getAllPosts()
const {postNum, handleClick} = useLoadMore();
return (
<main className="max-w-4xl mx-auto py-8">
<TypeWriter
words={["Welcome to my website!", "I'm excited to share", "my thoughts"]}
/>
{/* Container with flexbox */}
<div className="flex flex-col lg:flex-row lg:space-x-8">
{/* Left section: Blog posts */}
<div className="flex-1">
<ul>
{posts.slice(0, postNum).map((post) => (
<li key={post.slug} className="mb-4">
<Link href={`/blog/${post.slug}`}>
<h2 className="text-xl font-semibold hover:underline text-blue-500">
{post.title}
</h2>
<h1 className="text-gray-500">{post.description}</h1>
</Link>
<p className="text-gray-500">{post.date}</p>
</li>
))}
<button onClick={handleClick}>Load More</button>
</ul>
</div>
</div>
</main>
)
}
所以请启发我,我不知道为什么这不起作用。仅供参考,我使用 typescript 和 nextjs,如果这有帮助的话
从表面上看,问题在于您试图在服务器组件内部导入一个钩子。请注意,服务器组件不支持客户端功能,例如挂钩。 请参阅此处的表格,了解有关客户端和服务器组件可以做什么和不能做什么的更多信息。
要解决您的问题,只需将需要客户端功能的代码部分转换为客户端组件即可。例如,像这样定义这个新的客户端组件:
"use client";
// This is at components/BlogPosts.tsx
import Link from "next/link";
import { useLoadMore } from "./LoadMore";
export function BlogPosts({
posts,
}: {
posts: {
slug: string;
description: string;
title: string;
date: string;
}[];
}) {
// define your type here
const { postNum, handleClick } = useLoadMore();
return (
<div className="flex-1">
<ul>
{posts.slice(0, postNum).map((post) => (
<li key={post.slug} className="mb-4">
<Link href={`/blog/${post.slug}`}>
<h2 className="text-xl font-semibold hover:underline text-blue-500">
{post.title}
</h2>
<h1 className="text-gray-500">{post.description}</h1>
</Link>
<p className="text-gray-500">{post.date}</p>
</li>
))}
<button onClick={handleClick}>Load More</button>
</ul>
</div>
);
}
然后将此客户端组件导入到服务器端
Main.tsx
组件中,如下所示:
import { BlogPosts } from "../components/BlogPosts";
export default function Home() {
const posts = getAllPosts();
return (
<main className="max-w-4xl mx-auto py-8">
<TypeWriter
words={[
"Welcome to my website!",
"I'm excited to share",
"my thoughts",
]}
/>
{/* Container with flexbox */}
<div className="flex flex-col lg:flex-row lg:space-x-8">
{/* Left section: Blog posts */}
<BlogPosts posts={posts} />
</div>
</main>
);
}