【问题标题】:REACTJS Place variables inside JSON stringREACTJS 将变量放在 JSON 字符串中
【发布时间】:2022-01-18 11:39:17
【问题描述】:

我想知道是否可以将变量放入 JSON 字符串值中。

一些例子:(file.json)

{
  "type": "description",
  "description": "${this.name} is ${this.age} years old. ${this.name}'s favorite color is ${this.favColor}"
}

然后在 React 中:

data = require("file.json);
name = "John";
age = 20;
favColor = "blue";

渲染函数...

render() {
  return() {
    <p>{this.data.description}</p>
  }
}

有什么方法可以做这样的事情吗?目标是自动替换变量。

【问题讨论】:

  • 您当然可以这样做,但您必须手动查找和替换字符串。你可以很快找到如何做到这一点。
  • 这是不可能的,但是你可以写一个Person类,使用JSON数据初始化它,然后让description成为一个填充数据的函数。
  • 我想避免 find&replace,我认为有一种方法可以像在 php 中那样自动替换 var。
  • 如果您为其编写专用函数,则可以自动完成查找和替换。自动化程度能提高多少?
  • @ChrisG 这只是一个例子。在我的情况下,每个对象的描述都完全不同,因此它必须包含在 JSON 中

标签: javascript reactjs json variables replace


【解决方案1】:

您可以手动查找和替换字符串。类似下面的答案就可以了:https://stackoverflow.com/a/1408373/9150652

这在你的 React 组件中可能如下所示:

// Your JSON data as string
const json = `{
  "type": "description",
  "description": "{name} is {age} years old. {name}'s favorite color is {favColor}"
}`

// method to find and replace interpolate values
const interpolate = (str, values) => {
  return str.replace(/{([^{}]*)}/g,
      (a, b) => {
          const r = values[b];
          return typeof r === 'string' || typeof r === 'number' ? r : a;
      }
  );
};

const SomeComponent = () => {
  const values = {
    name: 'John',
    age: 27,
    favColor: 'red'
  };

  // Interpolate before parsing the JSON!
  const parsedJson = JSON.parse(interpolate(json, values));

  // Now you can use the object with the correct values filled in
  return <p>{parsedJson.description}</p>;
}

如果您使用 Class 组件,您甚至可以尝试传入 this 而不是 values 并使用本地值,类似于您在问题中的描述
(也许)也应该开箱即用。

【讨论】:

  • 我写了我的查找和替换函数。还是谢谢你。
猜你喜欢
  • 1970-01-01
  • 2020-09-03
  • 1970-01-01
  • 2019-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-29
相关资源
最近更新 更多