React Native中如何通过InjectJavascript获取WebView元素值并设置State
解决React Native WebView中通过InjectJavascript更新组件State的问题
我明白你遇到的困扰了——直接在injectJavaScript的代码里调用this.setState肯定行不通,因为这段JS是运行在WebView内部的浏览器上下文里,和你的React Native组件上下文完全隔离,根本访问不到组件实例的this对象,自然没法直接调用组件的setState方法。
下面是正确的实现思路和代码示例:
核心思路
我们需要通过消息传递的方式,把WebView里的HTML元素值传递回React Native组件,再在组件内部调用setState更新状态:
- 在注入的JS代码中,获取目标元素的值,通过
window.ReactNativeWebView.postMessage()发送给React Native - 在WebView组件上监听
onMessage事件,接收传递过来的数据后,再调用组件的setState更新状态
单数据更新示例
注入的JS脚本
const injectScript = ` // 获取目标元素的值 const dataValue = document.getElementById('data').value; // 只有当值不为空时才发送消息 if (dataValue.length > 0) { // 把值发送给React Native window.ReactNativeWebView.postMessage(dataValue); } `;
React Native WebView组件使用
<WebView source={{ uri: '你的网页地址' }} // 替换成你的实际网页地址 injectJavaScript={injectScript} // 监听WebView发来的消息 onMessage={(event) => { const receivedData = event.nativeEvent.data; // 在这里更新组件State this.setState({ data: receivedData }); }} />
多数据更新示例
如果需要同时传递多个元素的值,我们可以把数据打包成JSON字符串发送:
注入的JS脚本
const injectScript = ` const dataElement = document.getElementById('data'); const otherDataElement = document.getElementById('other-data'); // 确保两个元素的值都不为空 if (dataElement.value.length > 0 && otherDataElement.value.length > 0) { // 打包成JSON对象 const payload = JSON.stringify({ data: dataElement.value, otherData: otherDataElement.value }); // 发送JSON字符串 window.ReactNativeWebView.postMessage(payload); } `;
React Native WebView组件接收消息
<WebView source={{ uri: '你的网页地址' }} injectJavaScript={injectScript} onMessage={(event) => { // 解析JSON字符串 const payload = JSON.parse(event.nativeEvent.data); // 同时更新多个State变量 this.setState({ data: payload.data, otherData: payload.otherData }); }} />
为什么之前的代码无效?
你之前尝试的${this.setState({data: document.getElementById('data').value})}这种写法,本质是把React Native组件的setState方法直接拼接到WebView的JS代码里,但WebView的浏览器环境根本不知道this是什么(它指向的是WebView的window对象,不是你的React组件实例),所以这段代码执行时会报错,自然无法更新State。
内容的提问来源于stack exchange,提问作者Zain Budhwani
相关产品推荐
相关产品推荐

