我想知道是否可以將變數放入 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>
}
}
有什么辦法可以做這樣的事情嗎?目標是自動替換變數。
uj5u.com熱心網友回復:
您可以進行手動字串查找和替換。類似以下答案的內容就可以了: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使用本地值,類似于您在問題中描述它的方式
應該(也許)也可以開箱即用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/416001.html
標籤:
