使用变量在本机反应中渲染 unicode 字符

Has*_*aza 12 javascript unicode reactjs react-native

我正在尝试呈现一些 Unicode 形式的阿拉伯语文本。

我已经尝试使用 Text 组件来渲染它,例如

const arabic  = "سُبْحَانَ اللهِ وَبِحَمْدِهِ"


render(){
 return(
  <Text>
   {arabic}
  </Text>
 )
}
Run Code Online (Sandbox Code Playgroud)

它按原样呈现 Unicode,但以这种方式编写

render(){
 return(
  <Text>

   &#1587;&#1615;&#1576;&#1618;&#1581;&#1614;&#1575;&#1606;&#1614;  
   #1575;&#1604;&#1604;&#1607;&#1616; 
 &#1608;&#1614;&#1576;&#1616;&#1581;&#1614;&#1605;&#1618;&#1583;&#1616; 
 &#1607;&#1616;

  </Text>
 )
}
Run Code Online (Sandbox Code Playgroud)

呈现正确的输出

Tim*_*Tim 17

如果要在变量中存储 unicode 字符/html 实体,则需要将 html 实体替换为 unicode 编号。

例如:

const arabic = "&#1587;"; 
Run Code Online (Sandbox Code Playgroud)

需要替换为:

const arabic  = "\u0633";
Run Code Online (Sandbox Code Playgroud)

在线有几个 unicode 表,您可以在其中将 html 实体转换为原始 unicode 编号。

工作示例:

https://snack.expo.io/BJp-jL004

使用第二种方法更新:

您可以使用 npm 模块html-entities,而不是手动将 html 实体转换为 unicode 数字。这里最大的优点是,您可以使用常规<Text>组件来渲染您的角色。

下面是一个例子:

import { Html5Entities } from 'html-entities'; 
const arabic  = "&#1587;&#1615;&#1576;&#1618;&#1581;&#1614;&#1575;&#1606;&#1614; &#1575;&#1604;&#1604;&#1607;&#1616; &#1608;&#1614;&#1576;&#1616;&#1581;&#1614;&#1605;&#1618;&#1583;&#1616;&#1607;&#1616;"

render() {
    const entities = new Html5Entities();
    return (
      <SafeAreaView style={styles.container}>
        <View>
        <Text> {entities.decode(arabic)} </Text>
        </View>
      </SafeAreaView>
    );
  }
Run Code Online (Sandbox Code Playgroud)

输出:

演示

工作示例:

https://snack.expo.io/Hk5b3IykS