React - 用变量解析字符串 [英] React - Parse String with Variables

查看:38
本文介绍了React - 用变量解析字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串的 json 文件,其中也需要包含变量.(这不是选择,而是要求) 编辑(用于上下文) - Web 应用程序中的所有文本都是动态的.每个组件都有自己的键,有多个键值对,例如:

component_one":{标题":标题文本",副标题":副标题文本",list_item_one":列表项文本",list_item_two":列表项文本",list_item_three":列表项文本",按钮":按钮文本"},

字符串中的一项或多项需要引用该组件内的变量.

例如:

<代码>{text":这是我的示例字符串,其中包含需要插值的 {variable}";}

当我拉入文件并呈现字符串时,它不会插入 {variable} 部分.是否有最佳实践方法来在 react 中渲染这些变量?从 api 中获取文本文件后,我将其保存到上下文中.

 const Component = () =>{const { account } = useContext(AppContext);让变量 = '测试';返回 <div>{account.text}</div>;};

我也尝试过使用 dangerouslySetInnerHTML 但也没有用.

来自 api 调用:

 const getText = useCallback(async (token) => {尝试 {让文件 = process.env.REACT_APP_FILE_NAME;让响应 = 等待 api.get(`${file}`, {标题:{授权:`Bearer ${token}`,},});dispatch({ type: "SET_TEXT", text: response.data });} 抓住(错误){console.warn(`获取文本错误:${err}`);}}, []);

解决方案

我想建议以下解决方案,在名为 state 的对象中定义变量,然后按空格分割字符串 会给你一个像 ['string', 'with', '{variable}','that'] 这样的数组,循环遍历这个数组,当你找到一个以{ 尝试从中删除 {} 并使用该字符串访问状态:

 const Component = () =>{const { account } = useContext(AppContext);让状态={变量:'测试'};return 

{account.text.split(' ').map(str=>{if(str.startsWith('{')){return state[str.replace(/[{}]/g,'')]+' '//添加空格}别的{返回 str+' ';}})}

;};

检查这个例子

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}`);
    }
  }, []);

解决方案

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

这篇关于React - 用变量解析字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆