react-native-webview加载完成后如何跳转至用户自定义URI
React Native WebView 动态更新加载地址解决方案
你当前的代码存在三处错误:
- React Native 中 ref 绑定的实例对象统一挂载在
current属性下,直接操作webviewRef无法访问到真实 WebView 组件实例 - React Native 内置
Button组件的点击回调属性为onPress,而非 Web 端的onClick - 不可直接修改 WebView 实例的
source属性更新加载地址,需调用组件暴露的loadRequest方法实现
修正后的实现(基于ref操作)
import React, { useState, useRef } from 'react'; import { View, TextInput, Button, StyleSheet } from 'react-native'; import WebView from 'react-native-webview'; export default function App() { const [uriInput, setUri] = useState(''); const webviewRef = useRef(null); return ( <View style={styles.container}> <TextInput onChangeText={(text) => { setUri(text); }} style={styles.input} placeholder="输入要访问的地址" /> <Button title="Go!" onPress={() => { if(uriInput.trim()) { webviewRef.current?.loadRequest(uriInput); } }} /> <WebView ref={webviewRef} style={styles.webView} source={{ uri: "http://example.com" }} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, paddingTop: 40, }, input: { height: 40, borderColor: '#ccc', borderWidth: 1, marginHorizontal: 10, paddingHorizontal: 10, marginBottom: 10, }, webView: { flex: 1, } });
更简洁的实现(基于state绑定)
你也可以直接将WebView的source属性绑定到state变量,修改state即可自动触发地址更新,无需操作ref:
import React, { useState } from 'react'; import { View, TextInput, Button, StyleSheet } from 'react-native'; import WebView from 'react-native-webview'; export default function App() { const [uri, setUri] = useState("http://example.com"); const [uriInput, setUriInput] = useState(''); return ( <View style={styles.container}> <TextInput onChangeText={(text) => { setUriInput(text); }} style={styles.input} placeholder="输入要访问的地址" /> <Button title="Go!" onPress={() => { if(uriInput.trim()) { setUri(uriInput); } }} /> <WebView style={styles.webView} source={{ uri }} /> </View> ); } // 样式代码和上面实现一致
内容的提问来源于stack exchange,提问作者JohnWick
相关产品推荐
相关产品推荐

