React Native中如何将字符串转换为Base64?btoa()仅在开发者工具开启时可用
Hey Eranbo, I’ve dealt with this exact frustration before—btoa() is hit-or-miss in React Native because it’s a browser-specific API that isn’t fully supported in RN’s JavaScript runtime (whether you’re using Hermes or JSC). It only works with dev tools open because the dev environment injects some browser-like APIs temporarily. Here are two solid, reliable alternatives:
方法1:使用React Native内置的Buffer类
React Native’s JS environment includes Node.js-style Buffer support, which is the most straightforward and dependency-free way to handle base64 conversion.
// 字符串转Base64的函数 const convertStringToBase64 = (inputString) => { return Buffer.from(inputString).toString('base64'); }; // 示例用法 const originalString = "Testing base64 conversion in RN!"; const base64Result = convertStringToBase64(originalString); console.log(base64Result); // VGVzdGluZyBiYXNlNjQgY29udmVyc2lvbiBpbiBSTiE=
This works consistently whether dev tools are open or closed, and supports standard ASCII strings out of the box.
方法2:处理Unicode/非ASCII字符串
If you’re working with non-ASCII characters (like emojis, accented letters, or non-Latin scripts), you’ll want to ensure proper UTF-8 encoding first:
const convertUnicodeToBase64 = (unicodeString) => { // 先将字符串编码为UTF-8字节数组 const utf8Bytes = new TextEncoder().encode(unicodeString); // 再转换为Base64 return Buffer.from(utf8Bytes).toString('base64'); }; // 示例用法 const unicodeString = "Hello 🌍, こんにちは, 你好!"; const unicodeBase64 = convertUnicodeToBase64(unicodeString); console.log(unicodeBase64); // SGVsbG8g8J+OmCwg4p2k6Iie4p2k6K+VLCDeiMOoiQ==
为什么btoa()不可靠?
btoa() expects binary data or ASCII strings, and React Native’s runtime doesn’t include a full implementation of this browser API. When dev tools are enabled, the debug bridge injects a browser-like environment that makes btoa() work, but this isn’t available in production or when dev tools are closed.
Sticking with Buffer is the safest bet—it’s part of RN’s core runtime and behaves consistently across all environments.
内容的提问来源于stack exchange,提问作者Erab BO

