我想創建一個提要,就像 Instagram 一樣,每 10 個帖子后就會顯示一個 Google 廣告。我使用 Firebase 作為我的資料庫,使用 tailwind-CSS 作為樣式。我將如何使用 Google Ads 來實作此功能?
這是我顯示提要的代碼
Feed.js
import {React, useState, useEffect} from "react";
import Navbar from "./Navbar";
import Post from "./Post";
import { onSnapshot, collection, query, orderBy } from "@firebase/firestore";
import { db } from "../firebase";
function Feed() {
const [posts, setPosts] = useState([]);
useEffect(
() =>
onSnapshot(
query(collection(db, "posts"), orderBy("timestamp", "desc")),
(snapshot) => {
setPosts(snapshot.docs);
}
),
[db]
);
return (
<div>
<Navbar />
<div className="pb-72">
{posts.map((post) => (
<Post key={post.id} id={post.id} post={post.data()} />
))}
</div>
</div>
);
}
export default Feed;
uj5u.com熱心網友回復:
javascriptmap函式有第二個引數 - index- 它告訴您它正在迭代的陣列中專案的索引。因此,您需要進行兩個關鍵更改:
return (
<div>
<Navbar />
<div className="pb-72">
{posts.map((post, idx) => {
// If true, you're on the tenth post
const isTenthPost = (idx 1) % 10 === 0
// Note the addition of the React fragment brackets - your map call
// has to return a single React component, so we add this to handle
// the case where we want to return both the post and the Google ad.
return (
<>
<Post key={post.id} id={post.id} post={post.data()} />
{ isTenthPost && <GoogleAdComponent /> }
</>
)
})}
</div>
</div>
);
我不建議您完全復制和粘貼此內容,但它應該可以幫助您了解如何確定您是否在第 n 篇文章中以及如何有條件地顯示另一個組件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/466772.html
標籤:javascript 火力基地 谷歌云火库 下一个.js 顺风CSS
