我目前正在學(xué)習(xí)NextJS,我想建立一個(gè)展示我用它創(chuàng)建的多個(gè)專案的網(wǎng)站。
我有一個(gè)名為"Tag"的元件,它是一個(gè)帶有自訂文字的按鈕模板,我想透過props傳遞它:
export default function Tag({val}) { return( <> <p>{val}</p> </> ) }
然後,在我的Block元件中,我想根據(jù)透過props傳遞的陣列中的元素?cái)?shù)量來產(chǎn)生相應(yīng)數(shù)量的Tag元件:
import Tag from "./Tag" export default function Block({tags, name}) { return( <> <section> <div></div> <h2>{name}</h2> <div> {tags.forEach(tag => <Tag val={tag} />)} </div> </section> </> ) }
然後,這個(gè)Block元件在主頁中被呼叫:
import Block from './components/Block' export default function Home() { return ( <> <Block tags={["Webflow", "UI Design"]} name="Projet 1" /> </> ) }
問題是:沒有顯示任何標(biāo)籤。
我認(rèn)為問題與forEach方法有關(guān),因?yàn)楫?dāng)我嘗試在沒有forEach方法的情況下產(chǎn)生單一標(biāo)籤時(shí),它可以正常工作。
問題在哪?
你使用了forEach方法,但在這個(gè)函數(shù)中沒有回傳任何內(nèi)容。你可以數(shù)組的map方法。
{tags.map(tag => <Tag val={tag} />)}
const tags = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const result = tags.forEach(tag => tag)
console.log(result) //undefined
const mapResult = tags.map(tag => tag)
console.log(mapResult) //[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]