javascript 如何在 ReactJs 中渲染口音?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29472020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:35:28  来源:igfitidea点击:

How to render accents in ReactJs?

javascriptreactjs

提问by Lai32290

I'm trying render an element which has an accent character using ReactJSand JSX, but it's not returning what I wanted.

我正在尝试使用ReactJSJSX渲染一个带有重音字符的元素,但它没有返回我想要的。

My JSX:

我的JSX:

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

            </div>
        );
    }
});

React.render(
    <Orcamento/>,
    document.getElementById("orcamento")
);

My rendered javascript:

我呈现的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")
);

And my result in browser:

我在浏览器中的结果:

Or?§amento

I've set <meta charset="UTF-8">in my index file inside the headtag, accent characters works in page title and body if this word is typed direct in page content, but is not working when it's rendered by ReactJs

<meta charset="UTF-8">head标签内的索引文件中设置了重音字符,如果在页面内容中直接输入这个词,则重音字符在页面标题和正文中起作用,但在通过以下方式呈现时不起作用ReactJs

How can I fix this problem?

我该如何解决这个问题?

回答by Lai32290

I resolved! the problem is because I'm compiling JSXusing gulp, and file generated is not UTF-8, so I save as file in UTF-8that is working!

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

回答by André Pena

What you see, Or?§amento, it's a result of a UTF-8 byte array being rendered in ASCII, probably codepage ISO 8859-1.

您所看到的,Or?§amento这是 UTF-8 字节数组以 ASCII 格式呈现的结果,可能是代码页 ISO 8859-1

ReactJS doesn't support non-ASCII characters within HTML.

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

Try this:

试试这个:

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

            </div>;
        );
    }
});

Or simply replace or?amentoby Or&#231;amento.

或者干脆替换or?amentoOr&#231;amento.

This is well explained in the JSX gotchas.

这在JSX gotchas 中有很好的解释。

回答by Michael Benin

Also using the charset utf-8, try using this library: https://github.com/mathiasbynens/he

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

import { decode } from 'he';

class Post extends Component { 
  render() {
    <h1>{ decode(this.props.post.title) }</h1>  
  }
}