You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 18:57:03