Expo Android中React Native集成react-native-signature-canvas报错求助
问题描述
在基于Expo的Android平台React Native应用中集成react-native-signature-canvas实现签名功能时,出现以下错误:
ERROR Invariant Violation: Failed to call into JavaScript module method WebViewMessageHandler11.onMessage(). Module has not been registered as callable. Bridgeless Mode: false. Registered callable JavaScript modules (n = 12): Systrace, JSTimers, HeapCapture, SamplingProfiler, RCTLog, RCTDeviceEventEmitter, RCTNativeAppEventEmitter, GlobalPerformanceLogger, HMRClient, AppRegistry, RCTEventEmitter, RNCWebViewMessagingModule.
A frequent cause of the error is that the application entry file path is incorrect. This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native., js engine: hermes
使用的组件代码如下:
import SignatureScreen from "react-native-signature-canvas"; import { useRef } from "react"; const Sign = ({ text, onOK }) => { const ref = useRef(); // Called after ref.current.readSignature() reads a non-empty base64 string const handleOK = (signature) => { console.log(signature); onOK(signature); // Callback from Component props }; // Called after ref.current.readSignature() reads an empty string const handleEmpty = () => { console.log("Empty"); }; // Called after ref.current.clearSignature() const handleClear = () => { console.log("clear success!"); }; // Called after end of stroke const handleEnd = () => { ref.current.readSignature(); }; // Called after ref.current.getData() const handleData = (data) => { console.log(data); }; return ( <SignatureScreen ref={ref} onEnd={handleEnd} onOK={handleOK} onEmpty={handleEmpty} onClear={handleClear} onGetData={handleData} autoClear={true} descriptionText={text} /> ); }; export default Sign;
解决步骤
适配Expo WebView环境
Expo内置的WebView与react-native-signature-canvas依赖的原生WebView存在桥接冲突,先安装Expo官方WebView模块:npx expo install expo-webview替换为Expo兼容的签名组件
改用Expo官方维护的expo-signature-pad,无需原生配置,适配性更好:npx expo install expo-signature-pad修改组件代码为:
import { SignaturePad } from 'expo-signature-pad'; import { useRef } from 'react'; const Sign = ({ text, onOK }) => { const signatureRef = useRef(null); const handleSave = async () => { if (signatureRef.current) { const signature = await signatureRef.current.toDataURLAsync(); signature ? onOK(signature) : console.log('Empty'); } }; const handleClear = () => { if (signatureRef.current) { signatureRef.current.clearAsync(); console.log('clear success!'); } }; return ( <> <SignaturePad ref={signatureRef} style={{ width: '100%', height: 300, backgroundColor: '#f8f8f8' }} onEnd={handleSave} /> <button onPress={handleClear}>Clear</button> </> ); }; export default Sign;清理缓存重启项目
清除Expo缓存,避免旧bundle或缓存导致的模块注册异常:npx expo start --clear检查Bridgeless模式
确认项目未启用Bridgeless模式,Expo默认不开启该模式。若app.json或app.config.js中有相关配置,确保ios.bridgeless和android.bridgeless设为false。
内容的提问来源于stack exchange,提问作者Haythem Khiari

