RN传入数字返回拼音首字母的包

安装包 yarn add pinyin@^3.0.1 我当前项目的版本

切记不要安装4.0.0-alpha.0 这种版本号后面带字母的,会有问题

js 复制代码
import React, {useEffect} from 'react';
import {View, Text} from 'react-native';
import {pinyin} from 'pinyin';

const App = () => {
  // 定义一个函数来将汉字转为拼音并返回首字母
  const getFirstLetter = chineseChar => {
    // 使用 pinyin 库将汉字转为拼音数组
    const pinyinArray = pinyin(chineseChar, {
      style: pinyin.STYLE_FIRST_LETTER, // 使用首字母风格
    });
    // 如果转换成功,返回首字母;否则返回原字符(如果是英文的话已经被转换为大写了)
    return pinyinArray.length > 0
      ? pinyinArray[0][0].toUpperCase()
      : chineseChar;
  };
  // 测试函数
  const test = () => {
    const chineseChar = '你好';
    const chineseChar1 = 'a你好';
    const chineseChar2 = 'a你好';
    const chineseChar3 = 'a你a好a';
    const chineseChar4 = '你a好a';
    const chineseChar5 = '你a好';
    const chineseChar6 = '你好a';
    const chineseChar7 = 'abc';
    const chineseChar8 = '?,/';
    const firstLetter = getFirstLetter(chineseChar);
    const firstLetter1 = getFirstLetter(chineseChar1);
    const firstLetter2 = getFirstLetter(chineseChar2);
    const firstLetter3 = getFirstLetter(chineseChar3);
    const firstLetter4 = getFirstLetter(chineseChar4);
    const firstLetter5 = getFirstLetter(chineseChar5);
    const firstLetter6 = getFirstLetter(chineseChar6);
    const firstLetter7 = getFirstLetter(chineseChar7);
    const firstLetter8 = getFirstLetter(chineseChar8);
    // 上面那个函数将包含中文的直接转换后返回首字母,非中文的如果是英文则转换为大写直接返回,特殊字符也是直接返回
    console.log(firstLetter); // 输出:N
    console.log(firstLetter1); // 输出:A
    console.log(firstLetter2); // 输出:A
    console.log(firstLetter3); // 输出:A
    console.log(firstLetter4); // 输出:N
    console.log(firstLetter5); // 输出:N
    console.log(firstLetter6); // 输出:N
    console.log(firstLetter7); // 输出:ABC
    console.log(firstLetter8); // 输出:?
  };

  // 调用测试函数
  test();
  return (
    <View>
      <Text>111</Text>
    </View>
  );
};

export default App;
相关推荐
恋猫de小郭4 分钟前
你还用 IDE 吗? AI 狂欢时代下 Cursor 慌了, JetBrains 等 IDE 的未来是什么?
前端·flutter·ai编程
明月_清风10 分钟前
拒绝盲目 Git:VS Code 神级插件 GitLens 的 9 个进效杀手锏
前端·git
孟祥_成都12 分钟前
用 AI,0 基础复刻网页顶级特效!😀
前端·javascript·vibecoding
万少7 小时前
小龙虾(openclaw),轻松玩转自动发帖
前端·人工智能·后端
Jagger_9 小时前
抱怨到躺床关灯的一次 DIY 记录
前端
陈随易12 小时前
前端大咖mizchi不满Rust、TypeScript却爱上MoonBit
前端·后端·程序员
whinc13 小时前
🚀 两年小程序开发,我把踩过的坑做成了开源 Skills
前端·微信小程序·ai编程
sure28214 小时前
React Native中创建自定义渐变色
前端·react native
KKKK15 小时前
SSE(Server-Sent Events)流式传输原理和XStream实践
前端·javascript
子兮曰15 小时前
Humanizer-zh 实战:把 AI 初稿改成“能发布”的技术文章
前端·javascript·后端