【问题标题】:React getting error identifier or string literal or numeric literal expected反应获取错误标识符或字符串文字或预期的数字文字
【发布时间】:2021-01-13 20:15:12
【问题描述】:

在做一些代码时,我遇到了一些错误。 我有json作为

{
            "EmployeeId": "3094",
            "sectionName": "A&M Finance",
    },

但在 React 渲染中,我得到“&amp”文本在 A 和 M 之间,然后我试图找到相同的解决方案,刚刚听说过危险的 SetInnerHTML,我尝试复制相同的内容,但出现错误像标识符或字符串文字或数字文字预期

这是我尝试过的一段代码(在渲染中我只是调用了一个方法 truncateMethod,因为我还需要限制字长)

export function truncateMethod(sectionName, length) {
  if (sectionName.length > length) {
    const newVal = dangerouslySetInnerHTML={{__html: sectionName }}
    return newVal.slice(0, length).concat('...');
  }
  return newVal;
}

最后我想要实现的是我需要像 A&M Finance

那样渲染

你们能帮我做什么,或者如果你需要更多解释,我很乐意在 cmets 中提供帮助

所以可能有两件事 -> 要么帮助我在反应渲染中摆脱 &amp 文本 -> 或帮助我在使用 dangerouslysethtml 时解决错误(正在获取错误标识符或字符串文字或数字文字)

【问题讨论】:

    标签: html reactjs react-redux


    【解决方案1】:

    dangerouslySetInnerHTML is used in the JSX element,不在定义const。例如:

    <div dangerouslySetInnerHTML={truncateMethod(someString, 10)} />
    

    您的方法本身也有另一个错误。当if 条件为false 时,该方法返回undefined,因为您从未定义newVal。我怀疑你的意思是这样的:

    export function truncateMethod(sectionName, length) {
        if (sectionName.length > length) {
            return sectionName.slice(0, length).concat('...');
        }
        return sectionName;
    }
    

    【讨论】:

      【解决方案2】:

      问题可能是因为 truncateMethod 正在返回一个数组

       export function truncateMethod(sectionName, length) {
            if (sectionName.length > length) {
              const newVal = dangerouslySetInnerHTML={{__html: sectionName }}
              return newVal.slice(0, length).concat('...'); // here it's returning an array
            }
            return sectionName;
          }
      

      解决这个问题

      export function truncateMethod(sectionName, length) {
            if (sectionName.length > length) {
              return sectionName.substring(0, length).concat('...'); // return string
            }
            return newVal;
          }
      

      然后在 JSX 中添加这样的参数

      <Component dangerouslySetInnerHTML={{__html: truncateMethod(sectionName,5) }} />
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多