【问题标题】:Using symbols in JSX and React Native在 JSX 和 React Native 中使用符号
【发布时间】:2018-05-10 20:29:46
【问题描述】:

我想在我的 React Native 项目中使用 this symbol

我尝试使用这样的 Unicode 编码:

    var arrow = "U+0279C";

在 JSX 中:

   <Text>
      {arrow}
   </Text>

但是,这只是按字面意思显示编码:U+0279C

那么知道如何在 JSX 中使用符号吗?

【问题讨论】:

标签: react-native jsx


【解决方案1】:

您应该使用符号的 HTML 代码。

<Text>
    &#10140;
</Text>

如下文注释中所述..(重要的是,引号似乎不起作用)...

澄清一下:&lt;Text&gt;&amp;#10140;&lt;/Text&gt; 会起作用,但&lt;Text&gt;{ '&amp;#10140;' }&lt;/Text&gt; 不会。

【讨论】:

  • 澄清一下:&lt;Text&gt;&amp;#10140;&lt;/Text&gt; 可以,但&lt;Text&gt;{ '&amp;#10140;' }&lt;/Text&gt; 不行。
【解决方案2】:

将此函数用于以下格式的符号:& # 1 7 4 ;

/**
 * replaces /$#d\+/ symbol with actual symbols in the given string
 * 
 * Returns given string with symbol code replaced with actual symbol
 * 
 * @param {string} name 
 */
export function convertSymbolsFromCode(name = '') {
  let final = null;
  if (name) {
    const val = name.match(/&#\d+;/) ? name.match(/&#\d+;/)[0] : false; // need to check whether it is an actual symbol code
    if (val) {
      const num = val.match(/\d+;/) ? val.match(/\d+;/)[0] : false; // if symbol, then get numeric code
      if (num) {
        final = num.replace(/;/g, '');
      }
    }
    if (final) {
      name = name.replace(/&#\d+;/g, String.fromCharCode(final));
    }
  }
  return name;
}

用法

<Text>
   {convertSymbolsFromCode(this.state.unicode)}
 </Text>

【讨论】:

    【解决方案3】:

    提供的答案对我不起作用,因为我是从 API 动态检索 unicode 十六进制代码。我必须将它们作为 JavaScript 传递到 react-native jsx 代码中。

    以下答案对我有用: Concatenate unicode and variable

    我使用了String.fromCodePoint(parseInt(unicode, 16)),它成功了。

    例子:

    const unicode = unicodeHexValueFromApi //This value equals "05D2"
    
    return(<Text>{String.fromCodePoint(parseInt(unicode, 16))}</Text>)
    

    【讨论】:

      【解决方案4】:

      &lt;Text&gt;{"Any character"}&lt;/Text&gt;

      这对我有用。

      【讨论】:

      • 这不如提供一个真实的例子来回答 OP 的问题或使用类似箭头的符号而不是 "Any character"
      猜你喜欢
      • 1970-01-01
      • 2021-09-01
      • 2021-11-28
      • 2019-10-09
      • 2017-04-27
      • 2020-02-19
      • 2021-01-08
      • 2014-09-12
      • 1970-01-01
      相关资源
      最近更新 更多