在React中,如何将数据的值设置为代码的标签?

我有数据如下:

[
  {
    key: '1',
    type: 'Apple'
  },
  {
    key: '2',
    type: 'Pear'
  }
]

return <>
 ...
{
  cardList.map(card => {
    <Card key={card.key}> // 这里我想要填写card.type </Card>
  })
}
</>

也就是说,这里的需求是:

<Card key='1' >
  <Apple></Apple>
</Card>

<Card key='2' >
  <Pear></Pear>
</Card>

请问下,这里代码应该如何写呢?

阅读 2k
2 个回答
<>
    {React.createElement(tagName, {}, 'This is a dynamically created tag.')}
    </>

试试这个

import React from 'react';
import Apple from './Apple'; 
import Pear from './Pear'; 

const components = {
  Apple: Apple,
  Pear: Pear
};

const cardList = [
  {
    key: '1',
    type: 'Apple'
  },
  {
    key: '2',
    type: 'Pear'
  }
];

const MyComponent = () => {
  return (
    <>
      {
        cardList.map(card => {
          const SpecificCard = components[card.type];
          return (
            <Card key={card.key}>
              <SpecificCard />
            </Card>
          );
        })
      }
    </>
  );
};

export default MyComponent;
推荐问题
logo
Microsoft
子站问答
访问
宣传栏