英文:
Generating multiple NextJS Components
问题
I'm currently learning NextJS and I want to create a website that shows multiple projects that I've created with it.
I have a "Tag" component which is a sort of button template with custom text that I want to pass through props:
export default function Tag({ val }) {
return (
<>
<p>{val}</p>
</>
)
}
Then, in my Block component, I want to generate as many Tag components as there are in an array passed through props:
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>
</>
)
}
This Block component is then called in the main page:
import Block from './components/Block';
export default function Home() {
return (
<>
<Block tags={["Webflow", "UI Design"]} name="Projet 1" />
</>
)
}
The problem is: no tags show up.
I think the problem is linked to the forEach method because when I try to generate a single tag without the forEach method, it works.
Can you figure out the problem?
Thanks, Lucas.
英文:
I'm currently learning NextJS and I want to create a website that shows multiple projects that I've created with it.
I have a "Tag" component which is a sort of button template with custom text that I want to pass through props :
export default function Tag({val}) {
return(
<>
<p>{val}</p>
</>
)
}
Then, in my Block component, I want to generate as many Tag components as there are in an array passed through props :
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>
</>
)
}
This Block component is then called in the main page :
import Block from './components/Block'
export default function Home() {
return (
<>
<Block tags={["Webflow", "UI Design"]} name="Projet 1" />
</>
)
}
The problem is : no tags show up.
I think the problem is linked to the forEach method because when I try to generate a single tag without the forEach method, it works.
Can you figure out the problem ?
Thanks, Lucas.
答案1
得分: 1
你正在使用forEach,并且在此函数中没有返回任何内容。你可以使用array.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]
英文:
You are using forEach and nothing returns in this function. You can use array.map function.
{tags.map(tag => <Tag val={tag} />)}
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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]
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论