소스 검색

Imported custom iOS and Android webview docs (as-is, with warning)

Jamon Holmgren 6 년 전
부모
커밋
f54a37f9d9
2개의 변경된 파일484개의 추가작업 그리고 0개의 파일을 삭제
  1. 255
    0
      docs/Custom-Android.md
  2. 229
    0
      docs/Custom-iOS.md

+ 255
- 0
docs/Custom-Android.md 파일 보기

@@ -0,0 +1,255 @@
1
+**NOTE: This document was imported from [the original WebView documentation](https://github.com/facebook/react-native-website/blob/7d3e9e120e38a7ba928f6b173eb98f88b6f2f85f/docs/custom-webview-android.md). While it may prove useful, it has not been adapted to React Native WebView yet.**
2
+
3
+While the built-in web view has a lot of features, it is not possible to handle every use-case in React Native. You can, however, extend the web view with native code without forking React Native or duplicating all the existing web view code.
4
+
5
+Before you do this, you should be familiar with the concepts in [native UI components](native-components-android). You should also familiarise yourself with the [native code for web views](https://github.com/facebook/react-native/blob/master/ReactAndroid/src/main/java/com/facebook/react/views/webview/ReactWebViewManager.java), as you will have to use this as a reference when implementing new features—although a deep understanding is not required.
6
+
7
+## Native Code
8
+
9
+To get started, you'll need to create a subclass of `ReactWebViewManager`, `ReactWebView`, and `ReactWebViewClient`. In your view manager, you'll then need to override:
10
+
11
+* `createReactWebViewInstance`
12
+* `getName`
13
+* `addEventEmitters`
14
+
15
+```java
16
+@ReactModule(name = CustomWebViewManager.REACT_CLASS)
17
+public class CustomWebViewManager extends ReactWebViewManager {
18
+  /* This name must match what we're referring to in JS */
19
+  protected static final String REACT_CLASS = "RCTCustomWebView";
20
+
21
+  protected static class CustomWebViewClient extends ReactWebViewClient { }
22
+
23
+  protected static class CustomWebView extends ReactWebView {
24
+    public CustomWebView(ThemedReactContext reactContext) {
25
+      super(reactContext);
26
+    }
27
+  }
28
+
29
+  @Override
30
+  protected ReactWebView createReactWebViewInstance(ThemedReactContext reactContext) {
31
+    return new CustomWebView(reactContext);
32
+  }
33
+
34
+  @Override
35
+  public String getName() {
36
+    return REACT_CLASS;
37
+  }
38
+
39
+  @Override
40
+  protected void addEventEmitters(ThemedReactContext reactContext, WebView view) {
41
+    view.setWebViewClient(new CustomWebViewClient());
42
+  }
43
+}
44
+```
45
+
46
+You'll need to follow the usual steps to [register the module](native-modules-android.md#register-the-module).
47
+
48
+### Adding New Properties
49
+
50
+To add a new property, you'll need to add it to `CustomWebView`, and then expose it in `CustomWebViewManager`.
51
+
52
+```java
53
+public class CustomWebViewManager extends ReactWebViewManager {
54
+  ...
55
+
56
+  protected static class CustomWebView extends ReactWebView {
57
+    public CustomWebView(ThemedReactContext reactContext) {
58
+      super(reactContext);
59
+    }
60
+
61
+    protected @Nullable String mFinalUrl;
62
+
63
+    public void setFinalUrl(String url) {
64
+        mFinalUrl = url;
65
+    }
66
+
67
+    public String getFinalUrl() {
68
+        return mFinalUrl;
69
+    }
70
+  }
71
+
72
+  ...
73
+
74
+  @ReactProp(name = "finalUrl")
75
+  public void setFinalUrl(WebView view, String url) {
76
+    ((CustomWebView) view).setFinalUrl(url);
77
+  }
78
+}
79
+```
80
+
81
+### Adding New Events
82
+
83
+For events, you'll first need to make create event subclass.
84
+
85
+```java
86
+// NavigationCompletedEvent.java
87
+public class NavigationCompletedEvent extends Event<NavigationCompletedEvent> {
88
+  private WritableMap mParams;
89
+
90
+  public NavigationCompletedEvent(int viewTag, WritableMap params) {
91
+    super(viewTag);
92
+    this.mParams = params;
93
+  }
94
+
95
+  @Override
96
+  public String getEventName() {
97
+    return "navigationCompleted";
98
+  }
99
+
100
+  @Override
101
+  public void dispatch(RCTEventEmitter rctEventEmitter) {
102
+    init(getViewTag());
103
+    rctEventEmitter.receiveEvent(getViewTag(), getEventName(), mParams);
104
+  }
105
+}
106
+```
107
+
108
+You can trigger the event in your web view client. You can hook existing handlers if your events are based on them.
109
+
110
+You should refer to [ReactWebViewManager.java](https://github.com/facebook/react-native/blob/master/ReactAndroid/src/main/java/com/facebook/react/views/webview/ReactWebViewManager.java) in the React Native codebase to see what handlers are available and how they are implemented. You can extend any methods here to provide extra functionality.
111
+
112
+```java
113
+public class NavigationCompletedEvent extends Event<NavigationCompletedEvent> {
114
+  private WritableMap mParams;
115
+
116
+  public NavigationCompletedEvent(int viewTag, WritableMap params) {
117
+    super(viewTag);
118
+    this.mParams = params;
119
+  }
120
+
121
+  @Override
122
+  public String getEventName() {
123
+    return "navigationCompleted";
124
+  }
125
+
126
+  @Override
127
+  public void dispatch(RCTEventEmitter rctEventEmitter) {
128
+    init(getViewTag());
129
+    rctEventEmitter.receiveEvent(getViewTag(), getEventName(), mParams);
130
+  }
131
+}
132
+
133
+// CustomWebViewManager.java
134
+protected static class CustomWebViewClient extends ReactWebViewClient {
135
+  @Override
136
+  public boolean shouldOverrideUrlLoading(WebView view, String url) {
137
+    boolean shouldOverride = super.shouldOverrideUrlLoading(view, url);
138
+    String finalUrl = ((CustomWebView) view).getFinalUrl();
139
+
140
+    if (!shouldOverride && url != null && finalUrl != null && new String(url).equals(finalUrl)) {
141
+      final WritableMap params = Arguments.createMap();
142
+      dispatchEvent(view, new NavigationCompletedEvent(view.getId(), params));
143
+    }
144
+
145
+    return shouldOverride;
146
+  }
147
+}
148
+```
149
+
150
+Finally, you'll need to expose the events in `CustomWebViewManager` through `getExportedCustomDirectEventTypeConstants`. Note that currently, the default implementation returns `null`, but this may change in the future.
151
+
152
+```java
153
+public class CustomWebViewManager extends ReactWebViewManager {
154
+  ...
155
+
156
+  @Override
157
+  public @Nullable
158
+  Map getExportedCustomDirectEventTypeConstants() {
159
+    Map<String, Object> export = super.getExportedCustomDirectEventTypeConstants();
160
+    if (export == null) {
161
+      export = MapBuilder.newHashMap();
162
+    }
163
+    export.put("navigationCompleted", MapBuilder.of("registrationName", "onNavigationCompleted"));
164
+    return export;
165
+  }
166
+}
167
+```
168
+
169
+## JavaScript Interface
170
+
171
+To use your custom web view, you'll need to create a class for it. Your class must:
172
+
173
+* Export all the prop types from `WebView.propTypes`
174
+* Return a `WebView` component with the prop `nativeConfig.component` set to your native component (see below)
175
+
176
+To get your native component, you must use `requireNativeComponent`: the same as for regular custom components. However, you must pass in an extra third argument, `WebView.extraNativeComponentConfig`. This third argument contains prop types that are only required for native code.
177
+
178
+```javascript
179
+import React, {Component, PropTypes} from 'react';
180
+import {WebView, requireNativeComponent} from 'react-native';
181
+
182
+export default class CustomWebView extends Component {
183
+  static propTypes = WebView.propTypes;
184
+
185
+  render() {
186
+    return (
187
+      <WebView {...this.props} nativeConfig={{component: RCTCustomWebView}} />
188
+    );
189
+  }
190
+}
191
+
192
+const RCTCustomWebView = requireNativeComponent(
193
+  'RCTCustomWebView',
194
+  CustomWebView,
195
+  WebView.extraNativeComponentConfig
196
+);
197
+```
198
+
199
+If you want to add custom props to your native component, you can use `nativeConfig.props` on the web view.
200
+
201
+For events, the event handler must always be set to a function. This means it isn't safe to use the event handler directly from `this.props`, as the user might not have provided one. The standard approach is to create a event handler in your class, and then invoking the event handler given in `this.props` if it exists.
202
+
203
+If you are unsure how something should be implemented from the JS side, look at [WebView.android.js](https://github.com/facebook/react-native/blob/master/Libraries/Components/WebView/WebView.android.js) in the React Native source.
204
+
205
+```javascript
206
+export default class CustomWebView extends Component {
207
+  static propTypes = {
208
+    ...WebView.propTypes,
209
+    finalUrl: PropTypes.string,
210
+    onNavigationCompleted: PropTypes.func,
211
+  };
212
+
213
+  static defaultProps = {
214
+    finalUrl: 'about:blank',
215
+  };
216
+
217
+  _onNavigationCompleted = (event) => {
218
+    const {onNavigationCompleted} = this.props;
219
+    onNavigationCompleted && onNavigationCompleted(event);
220
+  };
221
+
222
+  render() {
223
+    return (
224
+      <WebView
225
+        {...this.props}
226
+        nativeConfig={{
227
+          component: RCTCustomWebView,
228
+          props: {
229
+            finalUrl: this.props.finalUrl,
230
+            onNavigationCompleted: this._onNavigationCompleted,
231
+          },
232
+        }}
233
+      />
234
+    );
235
+  }
236
+}
237
+```
238
+
239
+Just like for regular native components, you must provide all your prop types in the component to have them forwarded on to the native component. However, if you have some prop types that are only used internally in component, you can add them to the `nativeOnly` property of the third argument previously mentioned. For event handlers, you have to use the value `true` instead of a regular prop type.
240
+
241
+For example, if you wanted to add an internal event handler called `onScrollToBottom`, you would use,
242
+
243
+```javascript
244
+const RCTCustomWebView = requireNativeComponent(
245
+  'RCTCustomWebView',
246
+  CustomWebView,
247
+  {
248
+    ...WebView.extraNativeComponentConfig,
249
+    nativeOnly: {
250
+      ...WebView.extraNativeComponentConfig.nativeOnly,
251
+      onScrollToBottom: true,
252
+    },
253
+  }
254
+);
255
+```

+ 229
- 0
docs/Custom-iOS.md 파일 보기

@@ -0,0 +1,229 @@
1
+**NOTE: This document was imported from [the original WebView documentation](https://github.com/facebook/react-native-website/blob/7d3e9e120e38a7ba928f6b173eb98f88b6f2f85f/docs/custom-webview-ios.md). While it may prove useful, it has not been adapted to React Native WebView yet.**
2
+
3
+While the built-in web view has a lot of features, it is not possible to handle every use-case in React Native. You can, however, extend the web view with native code without forking React Native or duplicating all the existing web view code.
4
+
5
+Before you do this, you should be familiar with the concepts in [native UI components](native-components-ios). You should also familiarise yourself with the [native code for web views](https://github.com/facebook/react-native/blob/master/React/Views/RCTWebViewManager.m), as you will have to use this as a reference when implementing new features—although a deep understanding is not required.
6
+
7
+## Native Code
8
+
9
+Like for regular native components, you need a view manager and an web view.
10
+
11
+For the view, you'll need to make a subclass of `RCTWebView`.
12
+
13
+```objc
14
+// RCTCustomWebView.h
15
+#import <React/RCTWebView.h>
16
+
17
+@interface RCTCustomWebView : RCTWebView
18
+
19
+@end
20
+
21
+// RCTCustomWebView.m
22
+#import "RCTCustomWebView.h"
23
+
24
+@interface RCTCustomWebView ()
25
+
26
+@end
27
+
28
+@implementation RCTCustomWebView { }
29
+
30
+@end
31
+```
32
+
33
+For the view manager, you need to make a subclass `RCTWebViewManager`. You must still include:
34
+
35
+* `(UIView *)view` that returns your custom view
36
+* The `RCT_EXPORT_MODULE()` tag
37
+
38
+```objc
39
+// RCTCustomWebViewManager.h
40
+#import <React/RCTWebViewManager.h>
41
+
42
+@interface RCTCustomWebViewManager : RCTWebViewManager
43
+
44
+@end
45
+
46
+// RCTCustomWebViewManager.m
47
+#import "RCTCustomWebViewManager.h"
48
+#import "RCTCustomWebView.h"
49
+
50
+@interface RCTCustomWebViewManager () <RCTWebViewDelegate>
51
+
52
+@end
53
+
54
+@implementation RCTCustomWebViewManager { }
55
+
56
+RCT_EXPORT_MODULE()
57
+
58
+- (UIView *)view
59
+{
60
+  RCTCustomWebView *webView = [RCTCustomWebView new];
61
+  webView.delegate = self;
62
+  return webView;
63
+}
64
+
65
+@end
66
+```
67
+
68
+### Adding New Events and Properties
69
+
70
+Adding new properties and events is the same as regular UI components. For properties, you define an `@property` in the header. For events, you define a `RCTDirectEventBlock` in the view's `@interface`.
71
+
72
+```objc
73
+// RCTCustomWebView.h
74
+@property (nonatomic, copy) NSString *finalUrl;
75
+
76
+// RCTCustomWebView.m
77
+@interface RCTCustomWebView ()
78
+
79
+@property (nonatomic, copy) RCTDirectEventBlock onNavigationCompleted;
80
+
81
+@end
82
+```
83
+
84
+Then expose it in the view manager's `@implementation`.
85
+
86
+```objc
87
+// RCTCustomWebViewManager.m
88
+RCT_EXPORT_VIEW_PROPERTY(onNavigationCompleted, RCTDirectEventBlock)
89
+RCT_EXPORT_VIEW_PROPERTY(finalUrl, NSString)
90
+```
91
+
92
+### Extending Existing Events
93
+
94
+You should refer to [RCTWebView.m](https://github.com/facebook/react-native/blob/master/React/Views/RCTWebView.m) in the React Native codebase to see what handlers are available and how they are implemented. You can extend any methods here to provide extra functionality.
95
+
96
+By default, most methods aren't exposed from RCTWebView. If you need to expose them, you need to create an [Objective C category](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/CustomizingExistingClasses/CustomizingExistingClasses.html), and then expose all the methods you need to use.
97
+
98
+```objc
99
+// RCTWebView+Custom.h
100
+#import <React/RCTWebView.h>
101
+
102
+@interface RCTWebView (Custom)
103
+- (BOOL)webView:(__unused UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
104
+- (NSMutableDictionary<NSString *, id> *)baseEvent;
105
+@end
106
+```
107
+
108
+Once these are exposed, you can reference them in your custom web view class.
109
+
110
+```objc
111
+// RCTCustomWebView.m
112
+
113
+// Remember to import the category file.
114
+#import "RCTWebView+Custom.h"
115
+
116
+- (BOOL)webView:(__unused UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
117
+ navigationType:(UIWebViewNavigationType)navigationType
118
+{
119
+  BOOL allowed = [super webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
120
+
121
+  if (allowed) {
122
+    NSString* url = request.URL.absoluteString;
123
+    if (url && [url isEqualToString:_finalUrl]) {
124
+      if (_onNavigationCompleted) {
125
+        NSMutableDictionary<NSString *, id> *event = [self baseEvent];
126
+        _onNavigationCompleted(event);
127
+      }
128
+    }
129
+  }
130
+
131
+  return allowed;
132
+}
133
+```
134
+
135
+## JavaScript Interface
136
+
137
+To use your custom web view, you'll need to create a class for it. Your class must:
138
+
139
+* Export all the prop types from `WebView.propTypes`
140
+* Return a `WebView` component with the prop `nativeConfig.component` set to your native component (see below)
141
+
142
+To get your native component, you must use `requireNativeComponent`: the same as for regular custom components. However, you must pass in an extra third argument, `WebView.extraNativeComponentConfig`. This third argument contains prop types that are only required for native code.
143
+
144
+```javascript
145
+import React, {Component, PropTypes} from 'react';
146
+import {WebView, requireNativeComponent, NativeModules} from 'react-native';
147
+const {CustomWebViewManager} = NativeModules;
148
+
149
+export default class CustomWebView extends Component {
150
+  static propTypes = WebView.propTypes;
151
+
152
+  render() {
153
+    return (
154
+      <WebView
155
+        {...this.props}
156
+        nativeConfig={{
157
+          component: RCTCustomWebView,
158
+          viewManager: CustomWebViewManager,
159
+        }}
160
+      />
161
+    );
162
+  }
163
+}
164
+
165
+const RCTCustomWebView = requireNativeComponent(
166
+  'RCTCustomWebView',
167
+  CustomWebView,
168
+  WebView.extraNativeComponentConfig
169
+);
170
+```
171
+
172
+If you want to add custom props to your native component, you can use `nativeConfig.props` on the web view. For iOS, you should also set the `nativeConfig.viewManager` prop with your custom WebView ViewManager as in the example above.
173
+
174
+For events, the event handler must always be set to a function. This means it isn't safe to use the event handler directly from `this.props`, as the user might not have provided one. The standard approach is to create a event handler in your class, and then invoking the event handler given in `this.props` if it exists.
175
+
176
+If you are unsure how something should be implemented from the JS side, look at [WebView.ios.js](https://github.com/facebook/react-native/blob/master/Libraries/Components/WebView/WebView.ios.js) in the React Native source.
177
+
178
+```javascript
179
+export default class CustomWebView extends Component {
180
+  static propTypes = {
181
+    ...WebView.propTypes,
182
+    finalUrl: PropTypes.string,
183
+    onNavigationCompleted: PropTypes.func,
184
+  };
185
+
186
+  static defaultProps = {
187
+    finalUrl: 'about:blank',
188
+  };
189
+
190
+  _onNavigationCompleted = (event) => {
191
+    const {onNavigationCompleted} = this.props;
192
+    onNavigationCompleted && onNavigationCompleted(event);
193
+  };
194
+
195
+  render() {
196
+    return (
197
+      <WebView
198
+        {...this.props}
199
+        nativeConfig={{
200
+          component: RCTCustomWebView,
201
+          props: {
202
+            finalUrl: this.props.finalUrl,
203
+            onNavigationCompleted: this._onNavigationCompleted,
204
+          },
205
+          viewManager: CustomWebViewManager,
206
+        }}
207
+      />
208
+    );
209
+  }
210
+}
211
+```
212
+
213
+Just like for regular native components, you must provide all your prop types in the component to have them forwarded on to the native component. However, if you have some prop types that are only used internally in component, you can add them to the `nativeOnly` property of the third argument previously mentioned. For event handlers, you have to use the value `true` instead of a regular prop type.
214
+
215
+For example, if you wanted to add an internal event handler called `onScrollToBottom`, you would use,
216
+
217
+```javascript
218
+const RCTCustomWebView = requireNativeComponent(
219
+  'RCTCustomWebView',
220
+  CustomWebView,
221
+  {
222
+    ...WebView.extraNativeComponentConfig,
223
+    nativeOnly: {
224
+      ...WebView.extraNativeComponentConfig.nativeOnly,
225
+      onScrollToBottom: true,
226
+    },
227
+  }
228
+);
229
+```