소스 검색

chore(docs): Adds guide for handling navigation state changes (#144)

* Adds guide for handling navigation state changes

* Update Guide.md
Jamon Holmgren 5 년 전
부모
커밋
4ad7036733
1개의 변경된 파일62개의 추가작업 그리고 2개의 파일을 삭제
  1. 62
    2
      docs/Guide.md

+ 62
- 2
docs/Guide.md 파일 보기

@@ -43,13 +43,73 @@ class MyWeb extends Component {
43 43
   render() {
44 44
     return (
45 45
       <WebView
46
-        source={{uri: 'https://infinite.red/react-native'}}
46
+        source={{uri: 'https://facebook.github.io/react-native/'}}
47 47
       />
48 48
     );
49 49
   }
50 50
 }
51 51
 ```
52 52
 
53
+### Controlling navigation state changes
54
+
55
+Sometimes you want to intercept a user tapping on a link in your webview and do something different than navigating there in the webview. Here's some example code on how you might do that using the `onNavigationStateChange` function.
56
+
57
+```js
58
+import React, { Component } from 'react';
59
+import { WebView } from 'react-native-webview';
60
+
61
+class MyWeb extends Component {
62
+  webview = null;
63
+
64
+  render() {
65
+    return (
66
+      <WebView
67
+        ref={ref => (this.webview = ref)}
68
+        source={{uri: 'https://facebook.github.io/react-native/'}}
69
+        onNavigationStateChange={this.handleWebViewNavigationStateChange}
70
+      />
71
+    );
72
+  }
73
+
74
+  handleWebViewNavigationStateChange = newNavState => {
75
+    // newNavState looks something like this:
76
+    // {
77
+    //   url?: string;
78
+    //   title?: string;
79
+    //   loading?: boolean;
80
+    //   canGoBack?: boolean;
81
+    //   canGoForward?: boolean;
82
+    // }
83
+    const { url } = newNavState;
84
+    if (!url) return
85
+
86
+    // handle certain doctypes
87
+    if (url.includes('.pdf')) {
88
+      this.webview.stopLoading();
89
+      // open a modal with the PDF viewer
90
+    }
91
+
92
+    // one way to handle a successful form submit is via query strings
93
+    if (url.includes('?message=success')) {
94
+      this.webview.stopLoading();
95
+      // maybe close this view?
96
+    }
97
+
98
+    // one way to handle errors is via query string
99
+    if (url.includes('?errors=true')) {
100
+      this.webview.stopLoading();
101
+    }
102
+
103
+    // redirect somewhere else
104
+    if (url.includes('google.com')) {
105
+      const newURL = 'https://facebook.github.io/react-native/';
106
+      const redirectTo = 'window.location = "' + newURL + '"';
107
+      this.webview.injectJavaScript(redirectTo);
108
+    }
109
+  }
110
+}
111
+```
112
+
53 113
 ### Add support for File Upload
54 114
 
55 115
 ##### iOS
@@ -129,4 +189,4 @@ Add permission in AndroidManifest.xml:
129 189
 
130 190
   ......
131 191
 </manifest>
132
-```
192
+```