繁体   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