简体   繁体   English

在 React/TypeScript 中渲染一组组件?

[英]Render an array of components in React/TypeScript?

I'm currently trying to render an array of JSX Components.我目前正在尝试渲染一组 JSX 组件。 I see two possible ways for me to do this.我看到了两种可能的方法来做到这一点。

One(current approach): Make the array of type object that holds the properties of the component and then construct the JSX component in line using the array contents as props一(目前的做法):制作包含组件属性的类型对象数组,然后使用数组内容作为props构建JSX组件

const todos = { title:string,content:string }[];
todos.map((todo:{ title:string,content:string })=>{<TitleCard title={todo.title}/>;

Two: Make the array of type JSX elements so the array stores the pure JSX Element and just plops it down with a .map inside a render function.二:创建 JSX 元素类型的数组,以便该数组存储纯 JSX 元素,并在渲染函数中使用 .map 将其放下。 I find the first approach to be more clean, but it requires a bit more work in terms of constructing the JSX elements from the props in the array.我发现第一种方法更干净,但是在从数组中的 props 构造 JSX 元素方面需要做更多的工作。

Which approach would be the correct/best way to go about this?哪种方法是解决此问题的正确/最佳方法? Appreciate the help.感谢帮助。

I'm not sure if I understand your second approach but first one sounds good.我不确定我是否理解你的第二种方法,但第一种听起来不错。 I cleaned the code up a bit and this is the way to go:我清理了一些代码,这是要走的路:

 type Todo = {
   title:string,
   content: string
 }
    
 // this data(todos) probably will come from your props but I added some 
 // dummy data for demonstration purpose
 const todos: Todo[] = [
  {title:"title1", content:"content1"}, 
  {title:"title2",content:"content2"}
 ];
    
 const mappedTodosToRender = todos.map(({title})=>{<TitleCard key={title} title={title}/>;

 return (
  <>
    {mappedTodosToRender}
  </>
 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM