亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 React 中將 JS 對象中的組件作為 props 傳遞

在 React 中將 JS 對象中的組件作為 props 傳遞

大話西游666 2023-07-06 09:56:03
我正在讀取 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>
查看完整描述

2 回答

?
慕絲7291255

TA貢獻1859條經驗 獲得超6個贊

在您定義為的對象中:


{

  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>

    ))}

  )

}

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


查看完整回答
反對 回復 2023-07-06
?
動漫人物

TA貢獻1815條經驗 獲得超10個贊

我認為你應該直接傳遞對象中的圖標組件,如下所示:


const data = [

{

    title: "some title",

    desc: "some desc",

 },

 [

   {

     icon: <TwitterIcon />,

     title: "title 1",

     desc: "desc 1",

   } ...

然后在index.js中你可以這樣做(這樣傳遞props會更清楚):


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>

    ))}

  )

}


查看完整回答
反對 回復 2023-07-06
  • 2 回答
  • 0 關注
  • 145 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號