问题
I have a json file of strings that also need to have variables in them. (This is not by choice, by requirements) EDIT (for context) - All of the text within the web app is to be dynamic. Each component will have it's own key, with multiple key-value pairs such as:
"component_one": {
"heading": "Heading Text",
"subheading": "Subheading Text",
"list_item_one": "List Item Text",
"list_item_two": "List Item Text",
"list_item_three": "List Item Text",
"button": "Button Text"
},
where one or more items in the string need to reference a variable within that component.
So for example:
{
"text": "This is my example string with {variable} that needs to be interpolated"
}
When I pull in the file and render the string, it's not interpolating the {variable}
part. Is there a best practice approach to rendering these variables within react? I'm saving the text file to context after grabbing it from the api.
const Component = () => {
const { account } = useContext(AppContext);
let variable = 'testing';
return <div>{account.text}</div>;
};
I also tried using dangerouslySetInnerHTML
but that didn't work either.
From the api call:
const getText = useCallback(async (token) => {
try {
let file = process.env.REACT_APP_FILE_NAME;
let response = await api.get(`${file}`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
dispatch({ type: "SET_TEXT", text: response.data });
} catch (err) {
console.warn(`Get Text Error: ${err}`);
}
}, []);
回答1:
I want to suggest the following solution, define your variable inside an object called state
then split your string by space
which will give you an array like ['string', 'with', '{variable}','that']
, loop through this array and when you find a string that starts with {
try to remove {
and }
from it and access the state using that string :
const Component = () => {
const { account } = useContext(AppContext);
let state={ variable : 'testing'};
return <div>{account.text.split(' ').map(str=>{
if(str.startsWith('{')){
return state[str.replace(/[{}]/g,'')]+' ' //add space
}else{
return str+' ';
}
})}
</div>;
};
Check this example
来源:https://stackoverflow.com/questions/63617847/react-parse-string-with-variables