【问题标题】:How to refer to a nested array element in Reactjs?如何在 Reactjs 中引用嵌套数组元素?
【发布时间】:2023-02-10 16:05:50
【问题描述】:

我有一个在我的 app.js 中引用的配置文件。我需要使用数组中嵌套元素的键。这是数组结构。我需要参考联系元素下的标签。

export const detailConfig = [
  {
    name: "Pr1",
    shortDescription: "Pr1 is a health related product",
    longDescription: "Pr1 is a health related product",
    contacts: [
      { label : "a", link :"1" },
      { label : "b", link: "1" }
    ]
  },

  {
    name: "pr2",
    shortDescription: "Pr2 is a mobile related product",
    longDescription: "Pr2 is a mobile related product",
    contacts: [
      { label : "c", type :"1" },
      { label : "d", type: "1" }
    ]
  }
];

反应代码:

import "./styles.css";

import {detailConfig} from "./config"

export default function App() {
  return (
    <div className="App">
      {detailConfig.map(detailConfig=>
        <div>
      <h1>{detailConfig.name}</h1>
      <p>{detailConfig.contacts.label}</p>
      </div>

      )}
    </div>
  );
}

代码和演示: https://codesandbox.io/s/objective-wright-ekktrg?file=/src/App.js

【问题讨论】:

  • 你到底想做什么?您是要列出产品的所有可用联系人,还是只想列出任何可用的联系人?

标签: reactjs


【解决方案1】:

您的 contacts 属性本身就是一个数组。所以,你要么需要:

  1. 在它上面循环/映射并根据你的喜好渲染它的项目 (https://codesandbox.io/s/peaceful-frost-mnv2fw)
  2. 从中选择您想要的项目(例如,仅限第一个联系人 - contacts[0])并改用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-01
    • 2020-02-19
    • 2020-09-02
    • 2017-01-07
    • 1970-01-01
    • 2017-04-12
    • 2021-12-27
    • 2023-03-05
    相关资源
    最近更新 更多