【问题标题】:How to use map function to list the array in React?如何使用 map 函数列出 React 中的数组?
【发布时间】:2020-10-27 07:25:49
【问题描述】:

这是我的代码:

import React, { FunctionComponent } from 'react'

export const ListPage: FunctionComponent = () => {
 const list = [
  {
    title: 'I like React'
  },
  {
    title: 'I also like Angular'
  }
 ]

 const listTag = () => {
  list.map(
    item => {
     <h1>{item.title}</h1>
    }
  )
 }

 return(
  <listTag/>
 )
}

但我仍然收到错误消息,无法取出数组。

【问题讨论】:

  • 你得到的错误信息是什么?
  • “JSX.IntrinsicElements”类型上不存在属性“listTag”。

标签: arrays reactjs map-function react-functional-component


【解决方案1】:

试试这个:

import React, { FunctionComponent } from 'react'

export const ListPage: FunctionComponent = () => {
    const list = [
     {
       title: 'I like React'
     },
     {
       title: 'I also like Angular'
     }
    ];

    const ListTag = () => list.map(item => (<h1>{item.title}</h1>))

    return (
      <ListTag />
    )
}

注意:下面列出的代码中存在问题

const listTag = () => { //fist letter of component need to be captial
  list.map( // the value of `list.map()` needed to be return
    item => {
    <h1>{item.title}</h1> // here you are not returning the value to map function.
    }
  )
}

return(
  <listTag/> // If You are using any function component make sure the first letter is also captial.
)

【讨论】:

  • const ListTag = () => list.map((item) =>

    {item.title}

    ) 函数缺少返回类型。 'ListTag' 不能用作 JSX 组件。这是错误消息,有什么想法吗?
  • 你试过把`

    {item.title}

    `包装成( &lt;h1&gt;{item.title}&lt;/h1&gt;)
  • 还是同样的问题
  • 能否请您更新博客或与codesandbox分享您的代码
猜你喜欢
  • 2021-11-18
  • 2018-01-16
  • 2021-12-30
  • 2019-03-11
  • 1970-01-01
  • 2019-09-15
  • 2010-12-05
  • 2021-04-19
  • 1970-01-01
相关资源
最近更新 更多