【问题标题】:Passing String with HTML entity as a prop not rendered properly in material UI将带有 HTML 实体的字符串作为道具在材质 UI 中未正确呈现
【发布时间】:2020-07-11 09:14:01
【问题描述】:

我遇到了材质 UI 中的单选按钮问题。 Material UI 当前接受 value 作为 FormControlLabel 组件的道具。当我们传递一个带有如下所示 HTML 实体的字符串时,它会按预期进行解析。

<FormControlLabel value="female" label="I&#39;m male" />
output: I'm male

当我们将相同的字符串作为道具传递时,它没有被正确解析,并且特殊字符在发送时被显示。

const label="I&#39;m male";
<FormControlLabel value={value} label={label} />
output: I&#39;m male

我尝试在网上搜索此内容,但找不到任何相关主题。如果问题已经存在,请将我链接到该问题,或者如果有人有解决方案,请提供替代解决方案。下面是codeandbox链接。

https://codesandbox.io/s/material-demo-543y4

【问题讨论】:

  • 这不是 "utf-8" - 那是 HTML entity - 在 HTML 中使用,而不是在 javascript 中
  • 我会重新提出我的问题,谢谢@JaromandaX

标签: javascript reactjs radio-button material-ui radio-group


【解决方案1】:

&amp;....;HTML Entitiy - 这就是为什么它直接在 HTML 中而不是在 javascript 中使用时有效的原因

您需要对其进行解码才能在 javascript 中使用它

一种方法是在这里完成https://medium.com/@tertiumnon/js-how-to-decode-html-entities-8ea807a140e5

function decodeHTMLEntities(text) {
  var textArea = document.createElement('textarea');
  textArea.innerHTML = text;
  return textArea.value;
}

所以你会像这样使用它

const label=decodeHTMLEntities("I&#39;m male");

现代 javascript 中一种更简洁的方法是使用标记模板

const entityDecode = (() => {
    const el = document.createElement('textarea');
    return (strings) => {
        el.innerHTML = strings.join('');
        return el.value;
    }
})();
const label=entityDecode`I&#39;m male`;
console.log(label);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 2021-08-17
    相关资源
    最近更新 更多