在 React 中,我如何使用我的 props 之一来映射我的 JSON?

问题描述 投票:0回答:1

我想使用 props.type 编辑 H5 中 JSON 的映射,类似于我对 className 所做的操作,但我找不到正确的方法。

import text from "../../text/global.json";

function Card(props) {
  let col = props.col;
  let type = props.type;

  return (
    <>
      <Col className={`bg-white p-4 card-b col-md-${col}`}>
        <h5>{text.homepage.servicios.cards.${type}.title}</h5>
        <p>Litigio, Microfinanzas, Responsabilidad social y sustentabilidad.</p>
        <Button>Ver más</Button>
      </Col>
    </>
  );
}

我尝试了与 className 相同的方法,希望将 prop 用作字符串,但没有成功。

reactjs node.js json react-props
1个回答
0
投票

您似乎正在尝试使用动态属性(类型)来访问 JSON 文件中的特定属性。 JavaScript 中动态属性访问的正确语法是使用方括号

[]
。以下是修改代码的方法:

import text from "../../text/global.json";

function Card(props) {
  let col = props.col;
  let type = props.type;

  return (
    <>
      <Col className={`bg-white p-4 card-b col-md-${col}`}>
        <h5>{text.homepage.servicios.cards[type].title}</h5>
        <p>Litigio, Microfinanzas, Responsabilidad social y sustentabilidad.</p>
        <Button>Ver más</Button>
      </Col>
    </>
  );
}

在此修改中,

text.homepage.servicios.cards[type].title
将根据
type
的值动态访问属性。确保 JSON 文件中存在该属性类型,并且它包含必要的子属性,例如
title
。如果
type
不存在或与 JSON 中的任何属性不匹配,则可能会导致错误,因此您可能需要为此添加适当的验证。

© www.soinside.com 2019 - 2024. All rights reserved.