如何在ReactJs中渲染重音符号

How to render accents in ReactJs?

本文关键字:音符 符号 ReactJs      更新时间:2023-09-26

我正在尝试使用ReactJS和JSX渲染一个具有重音字符的元素,但它没有返回我想要的内容。

我的JSX:

var Orcamento = React.createClass({
    render: function() {
        return (
            <div>
                <h1>Orçamento</h1>
            </div>
        );
    }
});
React.render(
    <Orcamento/>,
    document.getElementById("orcamento")
);

我的渲染javascript:

var Orcamento = React.createClass({displayName: "Orcamento",
    render: function() {
        return (
            React.createElement("div", null, 
                React.createElement("h1", null, "Orçamento")
            )
        );
    }
});
React.render(
    React.createElement(Orcamento, null),
    document.getElementById("orcamento")
);

我在浏览器中的结果:

Orçamento

我已经在head标记内的索引文件中设置了<meta charset="UTF-8">,如果该单词直接在页面内容中键入,则重音字符在页面标题和正文中有效,但在ReactJs 呈现时不起作用

如何解决此问题?

我解决了!问题是因为我使用gulp编译JSX,而生成的文件不是UTF-8,所以我在UTF-8中保存为正在工作的文件!

您看到的Orçamento是UTF-8字节数组以ASCII(可能是代码页ISO 8859-1)呈现的结果。

ReactJS不支持HTML中的非ASCII字符。

试试这个:

var Orcamento = React.createClass({
    render: function() {
        return (
            <div>
                <h1> { 'Orçamento' } </h1>
            </div>;
        );
    }
});

或者简单地用Or&#231;amento替换Orçamento

这在JSX的讨论中得到了很好的解释。

同样使用字符集utf-8,尝试使用此库:https://github.com/mathiasbynens/he

import { decode } from 'he';
class Post extends Component { 
  render() {
    <h1>{ decode(this.props.post.title) }</h1>  
  }
}