React Native WebView中textarea粘贴内容后无法返回最新值问题
问题:React Native WebView中textarea粘贴内容后回传旧文本
在React Native的WebView组件内嵌入textarea元素,向该textarea粘贴内容后,回传给React Native的文本仍是粘贴前的旧内容。例如初始内容为「This is old text」,粘贴「This is new text」后,回传的依然是旧文本。
相关代码
<WebView style={{flex:1, marginTop:10, width: '100%', height: '100%', fontSize:46, }} onMessage={(event) => { editorOnChange(event.nativeEvent.data); }} source={{ html: ` <!DOCTYPE html> <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> </head> <body> <style> [contentEditable=true]:empty:not(:focus):before { content: attr(data-text); cursor: text; color: red; pointer-events:none; } #placeholder{ position:absolute; color:#BDBDBD;font-size:46px;outline:none; } #contentHtml{ font-size:38px; word-wrap: break-word; font-family: 'Roboto'; padding:8px; outline:none; border:none; width:100%; height:100vh; } </style> <textarea id="contentHtml" maxlength="500" rows="20" placeholder="Enter Comment...">${commentPlainText}</textarea> </body> </html> <script> document.addEventListener("DOMContentLoaded", function() { $(document).on("keyup paste", "#contentHtml", function(e){ if(e.type === "paste"){ alert($(this).val()); setTimeout(function () { alert($(this).val()); window.ReactNativeWebView.postMessage($(this).val()); }, 100); }else{ var contentValue = $(this).val(); window.ReactNativeWebView.postMessage(contentValue); } }); }); </script> `, }}> </WebView>
回传输出
"This is old text"
回调函数代码
const editorOnChange = (txt) => { console.log(txt); }
解决方案
问题出在paste事件的setTimeout回调中:普通函数作为setTimeout的回调时,内部的this指向全局的window对象,而非触发事件的textarea元素,所以获取到的是旧值。
可以通过两种方式修复:
方式1:提前保存textarea的引用
修改paste事件处理逻辑,先把当前textarea的引用存到变量中,再在setTimeout里使用:
$(document).on("keyup paste", "#contentHtml", function(e){ const $textarea = $(this); // 保存当前textarea的jQuery对象 if(e.type === "paste"){ alert($textarea.val()); setTimeout(function () { alert($textarea.val()); window.ReactNativeWebView.postMessage($textarea.val()); }, 100); }else{ var contentValue = $textarea.val(); window.ReactNativeWebView.postMessage(contentValue); } });
方式2:使用箭头函数
箭头函数不会绑定自己的this,会继承外层作用域的this,也就是触发事件的textarea元素:
$(document).on("keyup paste", "#contentHtml", function(e){ if(e.type === "paste"){ alert($(this).val()); setTimeout(() => { // 改用箭头函数 alert($(this).val()); window.ReactNativeWebView.postMessage($(this).val()); }, 100); }else{ var contentValue = $(this).val(); window.ReactNativeWebView.postMessage(contentValue); } });
内容的提问来源于stack exchange,提问作者redoc01
相关产品推荐
相关产品推荐

