REACTJS 将变量放在 JSON 字符串中
REACTJS Place variables inside JSON string
我想知道是否可以将变量放入 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>
}
}
有什么方法可以做这样的事情吗?目标是自动替换变量。
您可以进行手动字符串查找和替换。像下面这样的答案就可以了:
这在您的 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>;
}
If you use Class components, you could even try passing in this
instead of values
and use local values, similar to how you described it in your question
Should (maybe) work out of the box aswell.
我想知道是否可以将变量放入 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>
}
}
有什么方法可以做这样的事情吗?目标是自动替换变量。
您可以进行手动字符串查找和替换。像下面这样的答案就可以了:
这在您的 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>;
}
If you use Class components, you could even try passing in
this
instead ofvalues
and use local values, similar to how you described it in your question
Should (maybe) work out of the box aswell.