在 React 中将 JS 对象中的组件作为 props 传递

我正在读取 JS 对象(来自 JSX)并尝试传递组件的值,但它呈现为字符串。


我尝试放置组件(见下文icon的关键部分data),{}但这并没有帮助,因为data会出现错误。


这是文件的简化版本。


data.js如下:


const data = [

 {

    title: "some title",

    desc: "some desc",

 },

 [

   {

     icon: "<TwitterIcon />",

     title: "title 1",

     desc: "desc 1",

   },

   {

     icon: "<FacebookIcon />",

     title: "title 2",

     desc: "desc 2",

   },

 ],

]


export { data }

index.js读取data对象并作为 props 传递给AnotherComponent:


import { data } from "../path/to/data"

import AnotherComponent from "../path/to/AnotherComponent"


const Homepage = () => {


  return (

    <AnotherComponent {...data} />

  )

}

AnotherComponent.jsx如下:


import {TwitterIcon, FacebookIcon} from "../path/to/CustomIcons"


const AnotherComponent = ({ ...data}) => {


  return (

    {data[1].map(item => (

      <div>{item.icon}</div> // this prints string as opposed to rendering the component

      <div>{item.title}</div>

      <div>{item.desc}</div>

    ))}

  )

}

index.js返回:


<div><TwitterIcon /></div>

<div>title 1</div>

<div>desc 1</div>

<div><FacebookIcon /></div>

<div>title 2</div>

<div>desc 2</div>


大话西游666
浏览 108回答 2
2回答

慕丝7291255

在您定义为的对象中:{&nbsp; icon: "<TwitterIcon />",&nbsp; title: "title 1",&nbsp; desc: "desc 1",}不要使用"<TwitterIcon />"它总是返回一个字符串,而是使用TwitterIcon:{&nbsp; icon: TwitterIcon,&nbsp; title: "title 1",&nbsp; desc: "desc 1",}最后,在需要的地方调用它,如下所示:const AnotherComponent = ({ ...data}) => {&nbsp; return (&nbsp; &nbsp; {data[1].map(item => (&nbsp; &nbsp; &nbsp; <div><item.icon /></div> // HERE: check I'm calling item.icon as React Component&nbsp; &nbsp; &nbsp; <div>{item.title}</div>&nbsp; &nbsp; &nbsp; <div>{item.desc}</div>&nbsp; &nbsp; ))}&nbsp; )}通过这种方式,您可以将图标传递到您想要的任何地方,而不仅仅是传递字符串。因此,当您需要渲染时,您可以将其称为组件。我在工作中经常这样做。

动漫人物

我认为你应该直接传递对象中的图标组件,如下所示:const data = [{&nbsp; &nbsp; title: "some title",&nbsp; &nbsp; desc: "some desc",&nbsp;},&nbsp;[&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp;icon: <TwitterIcon />,&nbsp; &nbsp; &nbsp;title: "title 1",&nbsp; &nbsp; &nbsp;desc: "desc 1",&nbsp; &nbsp;} ...然后在index.js中你可以这样做(这样传递props会更清楚):const Homepage = () => {&nbsp; return (&nbsp; &nbsp; <AnotherComponent data={data} />&nbsp; )}现在在AnotherComponent.jsx中您可以执行以下操作:const AnotherComponent = ({data}) => {&nbsp; return (&nbsp; &nbsp; {data[1].map(item => (&nbsp; &nbsp; &nbsp; <div>{item.icon}</div>&nbsp; &nbsp; &nbsp; <div>{item.title}</div>&nbsp; &nbsp; &nbsp; <div>{item.desc}</div>&nbsp; &nbsp; ))}&nbsp; )}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript