Add props for overriding native component

Summary:
Opening a new PR for #10946 (see discussion there).

This PR builds upon #14775 (iOS ViewManager inheritance) and #14261 (more extensible Android WebView).

**Motivation**
When `WebView.android.js` and `WebView.ios.js` use `requireNativeComponent`, they are hard-coded to require `RCTWebView`. This means if you want to re-use the same JS-logic, but require a custom native WebView-implementation, you have to duplicate the entire JS-code files.

The same is true if you want to pass through any custom events or props, which you want to set on the custom native `WebView`.

What I'm trying to solve with this PR is to able to extend native WebView logic, and being able to re-use and extend existing WebView JS-logic.

This is done by adding a new `nativeConfig` prop on WebView. I've also moved the  extra `requireNativeComponent` config to `WebView.extraNativeComponentConfig` for easier re-use.

**Test plan**
jacobp100 has been kind enough to help me with docs for this new feature. So that is part of the PR and can be read for some information.

I've also created an example app which demonstrates how to use this functionality: https://github.com/cbrevik/webview-native-config-example

If you've implemented the native side as in the example repo above, it should be fairly easy to use from JavaScript like this:
```javascript
import React, { Component, PropTypes } from 'react';
import { WebView, requireNativeComponent, NativeModules } from 'react-native';
const { CustomWebViewManager } = NativeModules;

export default class CustomWebView extends Component {
  static propTypes = {
    ...WebView.propTypes,
    finalUrl: PropTypes.string,
    onNavigationCompleted: PropTypes.func,
  };

  _onNavigationCompleted = (event) => {
    const { onNavigationCompleted } = this.props;
    onNavigationCompleted && onNavigationCompleted(event);
  }

  render() {
    return (
      <WebView
        {...this.props}
        nativeConfig={{
          component: RCTCustomWebView,
          props: {
            finalUrl: this.props.finalUrl,
            onNavigationCompleted: this._onNavigationCompleted,
          },
          viewManager: CustomWebViewManager
        }}
      />
    );
  }
}

const RCTCustomWebView = requireNativeComponent(
  'RCTCustomWebView',
  CustomWebView,
  WebView.extraNativeComponentConfig
);
```

As you see, you require the custom native implementation at the bottom, and send in that along with any custom props with the `nativeConfig` prop on the `WebView`. You also send in the `viewManager` since iOS requires that for `startLoadWithResult`.

**Discussion**
As noted in the original PR, this could in principle be done with more React Native components, to make it easier for the community to re-use and extend native components.
Closes https://github.com/facebook/react-native/pull/15016

Differential Revision: D5701280

Pulled By: hramos

fbshipit-source-id: 6c3702654339b037ee81d190c623b8857550e972
This commit is contained in:
Christian Brevik 2017-09-19 15:49:44 -07:00 committed by Facebook Github Bot
parent ed77dbb5ae
commit f426a83d1b
8 changed files with 587 additions and 22 deletions

View File

@ -45,6 +45,14 @@ var defaultRenderLoading = () => (
* Renders a native WebView.
*/
class WebView extends React.Component {
static get extraNativeComponentConfig() {
return {
nativeOnly: {
messagingEnabled: PropTypes.bool,
},
};
}
static propTypes = {
...ViewPropTypes,
renderError: PropTypes.func,
@ -197,6 +205,26 @@ class WebView extends React.Component {
saveFormDataDisabled: PropTypes.bool,
/**
* Override the native component used to render the WebView. Enables a custom native
* WebView which uses the same JavaScript as the original WebView.
*/
nativeConfig: PropTypes.shape({
/*
* The native component used to render the WebView.
*/
component: PropTypes.any,
/*
* Set props directly on the native component WebView. Enables custom props which the
* original WebView doesn't pass through.
*/
props: PropTypes.object,
/*
* Set the ViewManager to use for communcation with the native side.
* @platform ios
*/
viewManager: PropTypes.object,
}),
/*
* Used on Android only, controls whether the given list of URL prefixes should
* make {@link com.facebook.react.views.webview.ReactWebViewClient} to launch a
* default activity intent for those URL instead of loading it within the webview.
@ -260,8 +288,12 @@ class WebView extends React.Component {
console.warn('WebView: `source.body` is not supported when using GET.');
}
const nativeConfig = this.props.nativeConfig || {};
let NativeWebView = nativeConfig.component || RCTWebView;
var webView =
<RCTWebView
<NativeWebView
ref={RCT_WEBVIEW_REF}
key="webViewKey"
style={webViewStyles}
@ -286,6 +318,7 @@ class WebView extends React.Component {
mixedContentMode={this.props.mixedContentMode}
saveFormDataDisabled={this.props.saveFormDataDisabled}
urlPrefixesForDefaultIntent={this.props.urlPrefixesForDefaultIntent}
{...nativeConfig.props}
/>;
return (
@ -402,11 +435,7 @@ class WebView extends React.Component {
}
}
var RCTWebView = requireNativeComponent('RCTWebView', WebView, {
nativeOnly: {
messagingEnabled: PropTypes.bool,
},
});
var RCTWebView = requireNativeComponent('RCTWebView', WebView, WebView.extraNativeComponentConfig);
var styles = StyleSheet.create({
container: {

View File

@ -116,6 +116,17 @@ var defaultRenderError = (errorDomain, errorCode, errorDesc) => (
class WebView extends React.Component {
static JSNavigationScheme = JSNavigationScheme;
static NavigationType = NavigationType;
static get extraNativeComponentConfig() {
return {
nativeOnly: {
onLoadingStart: true,
onLoadingError: true,
onLoadingFinish: true,
onMessage: true,
messagingEnabled: PropTypes.bool,
},
};
}
static propTypes = {
...ViewPropTypes,
@ -257,7 +268,7 @@ class WebView extends React.Component {
style: ViewPropTypes.style,
/**
* Determines the types of data converted to clickable URLs in the web views content.
* Determines the types of data converted to clickable URLs in the web view's content.
* By default only phone numbers are detected.
*
* You can provide one type or an array of many types.
@ -365,6 +376,27 @@ class WebView extends React.Component {
'always',
'compatibility'
]),
/**
* Override the native component used to render the WebView. Enables a custom native
* WebView which uses the same JavaScript as the original WebView.
*/
nativeConfig: PropTypes.shape({
/*
* The native component used to render the WebView.
*/
component: PropTypes.any,
/*
* Set props directly on the native component WebView. Enables custom props which the
* original WebView doesn't pass through.
*/
props: PropTypes.object,
/*
* Set the ViewManager to use for communcation with the native side.
* @platform ios
*/
viewManager: PropTypes.object,
}),
};
static defaultProps = {
@ -412,10 +444,14 @@ class WebView extends React.Component {
webViewStyles.push(styles.hidden);
}
const nativeConfig = this.props.nativeConfig || {};
const viewManager = nativeConfig.viewManager || RCTWebViewManager;
var onShouldStartLoadWithRequest = this.props.onShouldStartLoadWithRequest && ((event: Event) => {
var shouldStart = this.props.onShouldStartLoadWithRequest &&
this.props.onShouldStartLoadWithRequest(event.nativeEvent);
RCTWebViewManager.startLoadWithResult(!!shouldStart, event.nativeEvent.lockIdentifier);
viewManager.startLoadWithResult(!!shouldStart, event.nativeEvent.lockIdentifier);
});
var decelerationRate = processDecelerationRate(this.props.decelerationRate);
@ -429,8 +465,10 @@ class WebView extends React.Component {
const messagingEnabled = typeof this.props.onMessage === 'function';
const NativeWebView = nativeConfig.component || RCTWebView;
var webView =
<RCTWebView
<NativeWebView
ref={RCT_WEBVIEW_REF}
key="webViewKey"
style={webViewStyles}
@ -451,6 +489,7 @@ class WebView extends React.Component {
allowsInlineMediaPlayback={this.props.allowsInlineMediaPlayback}
mediaPlaybackRequiresUserAction={this.props.mediaPlaybackRequiresUserAction}
dataDetectorTypes={this.props.dataDetectorTypes}
{...nativeConfig.props}
/>;
return (
@ -590,15 +629,7 @@ class WebView extends React.Component {
}
}
var RCTWebView = requireNativeComponent('RCTWebView', WebView, {
nativeOnly: {
onLoadingStart: true,
onLoadingError: true,
onLoadingFinish: true,
onMessage: true,
messagingEnabled: PropTypes.bool,
},
});
var RCTWebView = requireNativeComponent('RCTWebView', WebView, WebView.extraNativeComponentConfig);
var styles = StyleSheet.create({
container: {

View File

@ -0,0 +1,267 @@
---
id: custom-webview-android
title: Custom WebView
layout: docs
category: Guides (Android)
permalink: docs/custom-webview-android.html
banner: ejected
next: headless-js-android
previous: native-components-android
---
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.
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.
## Native Code
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:
* `createReactWebViewInstance`
* `getName`
* `addEventEmitters`
```java
@ReactModule(name = CustomWebViewManager.REACT_CLASS)
public class CustomWebViewManager extends ReactWebViewManager {
/* This name must match what we're referring to in JS */
protected static final String REACT_CLASS = "RCTCustomWebView";
protected static class CustomWebViewClient extends ReactWebViewClient { }
protected static class CustomWebView extends ReactWebView {
public CustomWebView(ThemedReactContext reactContext) {
super(reactContext);
}
}
@Override
protected ReactWebView createReactWebViewInstance(ThemedReactContext reactContext) {
return new CustomWebView(reactContext);
}
@Override
public String getName() {
return REACT_CLASS;
}
@Override
protected void addEventEmitters(ThemedReactContext reactContext, WebView view) {
view.setWebViewClient(new CustomWebViewClient());
}
}
```
You'll need to follow the usual steps to [register the module](docs/native-modules-android.html#register-the-module).
### Adding New Properties
To add a new property, you'll need to add it to `CustomWebView`, and then expose it in `CustomWebViewManager`.
```java
public class CustomWebViewManager extends ReactWebViewManager {
...
protected static class CustomWebView extends ReactWebView {
public CustomWebView(ThemedReactContext reactContext) {
super(reactContext);
}
protected @Nullable String mFinalUrl;
public void setFinalUrl(String url) {
mFinalUrl = url;
}
public String getFinalUrl() {
return mFinalUrl;
}
}
...
@ReactProp(name = "finalUrl")
public void setFinalUrl(WebView view, String url) {
((CustomWebView) view).setFinalUrl(url);
}
}
```
### Adding New Events
For events, you'll first need to make create event subclass.
```java
// NavigationCompletedEvent.java
public class NavigationCompletedEvent extends Event<NavigationCompletedEvent> {
private WritableMap mParams;
public NavigationCompletedEvent(int viewTag, WritableMap params) {
super(viewTag);
this.mParams = params;
}
@Override
public String getEventName() {
return "navigationCompleted";
}
@Override
public void dispatch(RCTEventEmitter rctEventEmitter) {
init(getViewTag());
rctEventEmitter.receiveEvent(getViewTag(), getEventName(), mParams);
}
}
```
You can trigger the event in your web view client. You can hook existing handlers if your events are based on them.
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.
```java
public class NavigationCompletedEvent extends Event<NavigationCompletedEvent> {
private WritableMap mParams;
public NavigationCompletedEvent(int viewTag, WritableMap params) {
super(viewTag);
this.mParams = params;
}
@Override
public String getEventName() {
return "navigationCompleted";
}
@Override
public void dispatch(RCTEventEmitter rctEventEmitter) {
init(getViewTag());
rctEventEmitter.receiveEvent(getViewTag(), getEventName(), mParams);
}
}
// CustomWebViewManager.java
protected static class CustomWebViewClient extends ReactWebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
boolean shouldOverride = super.shouldOverrideUrlLoading(view, url);
String finalUrl = ((CustomWebView) view).getFinalUrl();
if (!shouldOverride && url != null && finalUrl != null && new String(url).equals(finalUrl)) {
final WritableMap params = Arguments.createMap();
dispatchEvent(view, new NavigationCompletedEvent(view.getId(), params));
}
return shouldOverride;
}
}
```
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.
```java
public class CustomWebViewManager extends ReactWebViewManager {
...
@Override
public @Nullable
Map getExportedCustomDirectEventTypeConstants() {
Map<String, Object> export = super.getExportedCustomDirectEventTypeConstants();
if (export == null) {
export = MapBuilder.newHashMap();
}
export.put("navigationCompleted", MapBuilder.of("registrationName", "onNavigationCompleted"));
return export;
}
}
```
## JavaScript Interface
To use your custom web view, you'll need to create a class for it. Your class must:
* Export all the prop types from `WebView.propTypes`
* Return a `WebView` component with the prop `nativeConfig.component` set to your native component (see below)
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.
```js
import React, { Component, PropTypes } from 'react';
import { WebView, requireNativeComponent } from 'react-native';
export default class CustomWebView extends Component {
static propTypes = WebView.propTypes
render() {
return (
<WebView
{...this.props}
nativeConfig={{ component: RCTCustomWebView }}
/>
);
}
}
const RCTCustomWebView = requireNativeComponent(
'RCTCustomWebView',
CustomWebView,
WebView.extraNativeComponentConfig
);
```
If you want to add custom props to your native component, you can use `nativeConfig.props` on the web view.
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.
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.
```js
export default class CustomWebView extends Component {
static propTypes = {
...WebView.propTypes,
finalUrl: PropTypes.string,
onNavigationCompleted: PropTypes.func,
};
static defaultProps = {
finalUrl: 'about:blank',
};
_onNavigationCompleted = (event) => {
const { onNavigationCompleted } = this.props;
onNavigationCompleted && onNavigationCompleted(event);
}
render() {
return (
<WebView
{...this.props}
nativeConfig={{
component: RCTCustomWebView,
props: {
finalUrl: this.props.finalUrl,
onNavigationCompleted: this._onNavigationCompleted,
}
}}
/>
);
}
}
```
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.
For example, if you wanted to add an internal event handler called `onScrollToBottom`, you would use,
```js
const RCTCustomWebView = requireNativeComponent(
'RCTCustomWebView',
CustomWebView,
{
...WebView.extraNativeComponentConfig,
nativeOnly: {
...WebView.extraNativeComponentConfig.nativeOnly,
onScrollToBottom: true,
},
}
);
```

238
docs/CustomWebViewIOS.md Normal file
View File

@ -0,0 +1,238 @@
---
id: custom-webview-ios
title: Custom WebView
layout: docs
category: Guides (iOS)
permalink: docs/custom-webview-ios.html
banner: ejected
next: linking-libraries-ios
previous: native-components-ios
---
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.
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.
## Native Code
Like for regular native components, you need a view manager and an web view.
For the view, you'll need to make a subclass of `RCTWebView`.
```objc
// RCTCustomWebView.h
#import <React/RCTWebView.h>
@interface RCTCustomWebView : RCTWebView
@end
// RCTCustomWebView.m
#import "RCTCustomWebView.h"
@interface RCTCustomWebView ()
@end
@implementation RCTCustomWebView { }
@end
```
For the view manager, you need to make a subclass `RCTWebViewManager`. You must still include:
* `(UIView *)view` that returns your custom view
* The `RCT_EXPORT_MODULE()` tag
```objc
// RCTCustomWebViewManager.h
#import <React/RCTWebViewManager.h>
@interface RCTCustomWebViewManager : RCTWebViewManager
@end
// RCTCustomWebViewManager.m
#import "RCTCustomWebViewManager.h"
#import "RCTCustomWebView.h"
@interface RCTCustomWebViewManager () <RCTWebViewDelegate>
@end
@implementation RCTCustomWebViewManager { }
RCT_EXPORT_MODULE()
- (UIView *)view
{
RCTCustomWebView *webView = [RCTCustomWebView new];
webView.delegate = self;
return webView;
}
@end
```
### Adding New Events and Properties
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`.
```objc
// RCTCustomWebView.h
@property (nonatomic, copy) NSString *finalUrl;
// RCTCustomWebView.m
@interface RCTCustomWebView ()
@property (nonatomic, copy) RCTDirectEventBlock onNavigationCompleted;
@end
```
Then expose it in the view manager's `@implementation`.
```objc
// RCTCustomWebViewManager.m
RCT_EXPORT_VIEW_PROPERTY(onNavigationCompleted, RCTDirectEventBlock)
RCT_EXPORT_VIEW_PROPERTY(finalUrl, NSString)
```
### Extending Existing Events
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.
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.
```objc
// RCTWebView+Custom.h
#import <React/RCTWebView.h>
@interface RCTWebView (Custom)
- (BOOL)webView:(__unused UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
- (NSMutableDictionary<NSString *, id> *)baseEvent;
@end
```
Once these are exposed, you can reference them in your custom web view class.
```objc
// RCTCustomWebView.m
// Remember to import the category file.
#import "RCTWebView+Custom.h"
- (BOOL)webView:(__unused UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
navigationType:(UIWebViewNavigationType)navigationType
{
BOOL allowed = [super webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
if (allowed) {
NSString* url = request.URL.absoluteString;
if (url && [url isEqualToString:_finalUrl]) {
if (_onNavigationCompleted) {
NSMutableDictionary<NSString *, id> *event = [self baseEvent];
_onNavigationCompleted(event);
}
}
}
return allowed;
}
```
## JavaScript Interface
To use your custom web view, you'll need to create a class for it. Your class must:
* Export all the prop types from `WebView.propTypes`
* Return a `WebView` component with the prop `nativeConfig.component` set to your native component (see below)
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.
```js
import React, { Component, PropTypes } from 'react';
import { WebView, requireNativeComponent, NativeModules } from 'react-native';
const { CustomWebViewManager } = NativeModules;
export default class CustomWebView extends Component {
static propTypes = WebView.propTypes
render() {
return (
<WebView
{...this.props}
nativeConfig={{
component: RCTCustomWebView,
viewManager: CustomWebViewManager
}}
/>
);
}
}
const RCTCustomWebView = requireNativeComponent(
'RCTCustomWebView',
CustomWebView,
WebView.extraNativeComponentConfig
);
```
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.
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.
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.
```js
export default class CustomWebView extends Component {
static propTypes = {
...WebView.propTypes,
finalUrl: PropTypes.string,
onNavigationCompleted: PropTypes.func,
};
static defaultProps = {
finalUrl: 'about:blank',
};
_onNavigationCompleted = (event) => {
const { onNavigationCompleted } = this.props;
onNavigationCompleted && onNavigationCompleted(event);
}
render() {
return (
<WebView
{...this.props}
nativeConfig={{
component: RCTCustomWebView,
props: {
finalUrl: this.props.finalUrl,
onNavigationCompleted: this._onNavigationCompleted,
},
viewManager: CustomWebViewManager
}}
/>
);
}
}
```
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.
For example, if you wanted to add an internal event handler called `onScrollToBottom`, you would use,
```js
const RCTCustomWebView = requireNativeComponent(
'RCTCustomWebView',
CustomWebView,
{
...WebView.extraNativeComponentConfig,
nativeOnly: {
...WebView.extraNativeComponentConfig.nativeOnly,
onScrollToBottom: true,
},
}
);
```

View File

@ -6,7 +6,7 @@ category: Guides (Android)
permalink: docs/headless-js-android.html
banner: ejected
next: signed-apk-android
previous: native-components-android
previous: custom-webview-android
---
Headless JS is a way to run tasks in JavaScript while your app is in the background. It can be used, for example, to sync fresh data, handle push notifications, or play music.

View File

@ -6,7 +6,7 @@ category: Guides (iOS)
permalink: docs/linking-libraries-ios.html
banner: ejected
next: running-on-simulator-ios
previous: native-components-ios
previous: custom-webview-ios
---
Not every app uses all the native capabilities, and including the code to support

View File

@ -5,7 +5,7 @@ layout: docs
category: Guides (Android)
permalink: docs/native-components-android.html
banner: ejected
next: headless-js-android
next: custom-webview-android
previous: native-modules-android
---

View File

@ -5,7 +5,7 @@ layout: docs
category: Guides (iOS)
permalink: docs/native-components-ios.html
banner: ejected
next: linking-libraries-ios
next: custom-webview-ios
previous: native-modules-ios
---