如果有有效图像,我只想为页面上的每个帖子显示图像。如果没有图像,
if(!post.image_url)
我想显示标题“图像不可用”,但是我不确定如何解决这个问题,因为据我所知,我无法在 JSX 中编写此内容。
这是我的代码,任何帮助将不胜感激
import Link from "next/link";
import Image from "next/image";
import { revalidatePath } from "next/cache";
export default async function Page({ params }) {
console.log(params.posts);
const posts = (await sql`SELECT * FROM posts01`).rows;
return (
<div className="p-4">
<h1 className="text-3xl font-bold mb-4"> Posts</h1>
<div key={posts.post_id}>
{posts.map((post) => (
<div key={post.id}>
<Link
href={`/allPosts/${post.post_id}`}
className="text-xl font-bold hover:underline mb-2"
>
<h3 className="text-xl font-bold hover:underline mb-2">
{post.title}
</h3>
<h5 className="text-lg">{post.content}</h5>
</Link>
{/* // if there is no image, display image unavailable text */}
{<Image src={post.image_url} alt="" width={300} height={300} />}
</div>
))}
</div>
</div>
);
}
您可以在 JSX 中使用内联
if/else
,如下所示:
return (
<div className="p-4">
<h1 className="text-3xl font-bold mb-4"> Posts</h1>
<div key={posts.post_id}>
{posts.map((post) => (
<div key={post.id}>
<Link
href={`/allPosts/${post.post_id}`}
className="text-xl font-bold hover:underline mb-2"
>
<h3 className="text-xl font-bold hover:underline mb-2">
{post.title}
</h3>
<h5 className="text-lg">{post.content}</h5>
</Link>
{
(post.image_url)
? <Image src={post.image_url} alt="" width={300} height={300} />
: <p>Sorry the image is unavailable</p>
}
</div>
))}
</div>
</div>
);