通过动态道具react访问javascript对象嵌套值

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

是否可以使用动态 props 来获取 javascript 对象的嵌套值,如下所示,因为我遇到了错误。请建议我任何解决方案。

组件。

import Link from "next/link";
import { info } from "@/lib/info";

export default function Tip({ name }) {
  return (
      <div>
        <div>
          <header>
            <p className="text-sky-400"> {info.${name}.title}</p>
          </header>
          <div>
            <div className="max-w-80">
              <p className="text-justify">{info.${name}.content}</p>
              <Link
                className="flex text-sky-700 pl-2 font-bold justify-end"
                target="blank"
                href={info.${name}.href}
              >
                Read more ...
              </Link>
            </div>
          </div>
        </div >
  );
}

使用组件。

<Tip name="accruedinterest" />

数组

export const info = {
  acrruedinterest: {
    title: "accrued interest",
    content:
      "In finance, accrued interest is the interest on a bond or loan that has accumulated since the principal investment, or since the previous coupon payment if there has been one already.",
    href: "https://en.wikipedia.org/wiki/Accrued_interest",
  },
  acrruedcosine: {
    title: "inverse cosine",
    content:
      "The inverse trigonometric functions are the inverses of the sine, cosine, tangent, cotangent, secant, and cosecant functions, and are used to obtain an angle from any of the angle's trigonometric ratios.",
    href: "https://en.wikipedia.org/wiki/Inverse_trigonometric_functions",
  },
  inversehyperbolic: {
    title: "inverse hyperbolic",
    content:
      "In mathematics, the inverse hyperbolic functions are invers of the hyperbolic functions, analogous to the inverse circular functions. There are six in common use: inverse hyperbolic sine, inverse hyperbolic cosine, inverse hyperbolic tangent, inverse hyperbolic cosecant, inverse hyperbolic secant, and inverse hyperbolic cotangent.",
    href: "https://en.wikipedia.org/wiki/Inverse_hyperbolic_functions",
  },
} 
reactjs arrays dynamic
1个回答
0
投票

您不能将点表示法与模板字符串一起使用来访问 JavaScript 对象中的属性。相反,您应该使用像

info[name]
这样的括号表示法来动态检索嵌套值。

这是代码的更新版本:

<p className="text-sky-400">{info[name]?.title}</p>

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