React Javascript 显示/解码 unicode 字符

IT技术 javascript reactjs
2021-05-03 11:19:20

我有一个需要转换的 unicode 字符串。我需要将带有 \u00f3 的字符串渲染为 ó。这是一个例子,它应该发生在所有其他类型的字符上,á、í、ú...

我有以下基本代码:https : //jsfiddle.net/dddf7o70/

我需要转换

<Hello name="Informaci\u00f3n" />

进入

Información
4个回答

只需将其作为 JS 字符串传递:

<Hello name={'Informaci\u00f3n'} />

无需进行任何手动处理(容易出错)。

小提琴:https : //jsfiddle.net/dddf7o70/5/

如果您必须使用字符串,无论出于何种原因,其中的\u....代码实际上是那些代码而不是真正的字母,请将它们转换为数字,然后使用 String.fromCharCode() 将这些数字转换为真正的字母。我们可以使用正则表达式替换处理程序函数:

function convertUnicode(input) {
  return input.replace(/\\u[0-9a-fA-F]{4}/g,function(a,b) {
    var charcode = parseInt(b,16);
    return String.fromCharCode(charcode);
  });
}

var Hello = React.createClass({
  getInitialState: function() {
    return {
      name: convertUnicode(this.props.name)
    };
  },
  render: function() {
    return <div>Hello {this.state.name}</div>;
  }
});

React.render(
  <Hello name="Informaci\u00f3n" />,
  document.getElementById('container')
);

小提琴:https : //jsfiddle.net/cq7o4zgb/

React 使用危险的SetInnerHTML属性自动转换Unicode

有关更多信息,请参阅:https : //reactjs.org/docs/dom-elements.html

export default class Hello extends Component {

render() {
    return (
        <div>
            <div dangerouslySetInnerHTML={{ __html: this.props.name}}></div>
        </div>
    );
  }
}

要将 unicode 写入您render()jsx,您可以:

<div>{'First \u00b7 Second'}</div>

, 或者

<div>{'First ' + String.fromCharCode(183) + ' Second'}</div>

如果使用库和其他字体执行此操作,请确保首先导入您的字体,确保您正在使用font-family: myFont(即"Font Awesome 5 Free")。并确保您使用的 unicode 是准确的。