簡體   English   中英

將 JS 對象中的組件作為 React 中的道具傳遞

[英]Pass Component from JS Object as props in React

我正在從 JS 對象(來自 JSX)讀取並嘗試傳遞組件的值,但它呈現為字符串。

我嘗試在{}放置組件(在data icon鍵中,見下文),但這無濟於事,因為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對象並作為道具傳遞給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>

在您定義的對象中:

{
  icon: "<TwitterIcon />",
  title: "title 1",
  desc: "desc 1",
}

不要使用"<TwitterIcon />"它總是會返回一個字符串,而是使用TwitterIcon

{
  icon: TwitterIcon,
  title: "title 1",
  desc: "desc 1",
}

最后,在需要的地方調用它,如下所示:

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

  return (
    {data[1].map(item => (
      <div><item.icon /></div> // HERE: check I'm calling item.icon as React Component
      <div>{item.title}</div>
      <div>{item.desc}</div>
    ))}
  )
}

通過這種方式,您可以將圖標傳遞到您想要的任何位置,而不僅僅是傳遞一個字符串。 因此,您可以在需要渲染時將其稱為 Component。 我在工作中經常這樣做。

我認為您應該直接傳遞object 中的 icon 組件,如下所示:

const data = [
{
    title: "some title",
    desc: "some desc",
 },
 [
   {
     icon: <TwitterIcon />,
     title: "title 1",
     desc: "desc 1",
   } ...

然后在index.js 中你可以做(​​像這樣傳遞道具更清楚):

const Homepage = () => {
  return (
    <AnotherComponent data={data} />
  )
}

現在在AnotherComponent.jsx 中,您可以執行以下操作:

const AnotherComponent = ({data}) => {
  return (
    {data[1].map(item => (
      <div>{item.icon}</div>
      <div>{item.title}</div>
      <div>{item.desc}</div>
    ))}
  )
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM