React Native UI 组件方法

React Native UI Component Method

我正在为 objective-c 中的 React Native 创建我自己的自定义 ui 组件,到目前为止一切正常,除了我似乎无法在我的组件上调用任何方法。这是我的 objective-c

#import "RNTWebViewManager.h"
#import <WebKit/WebKit.h>

@interface RNTWebViewManager()

@property (strong, nonatomic) WKWebView *webView;

@end

@implementation RNTWebViewManager

@synthesize webView;

RCT_EXPORT_MODULE()

- (UIView *)view {
  webView = [[WKWebView alloc] init];
  return  webView;
}

RCT_EXPORT_METHOD(loadWebsite:(NSString *)url)
{
  RCTLogInfo(@"Opening url %@",url);
  [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
};

@end

这是我对应的 javascript 代码:

import React, { Component } from 'react';
import {
  requireNativeComponent,
  AppRegistry,
  StyleSheet,
  Button,
  Text,
  View
} from 'react-native';

// Load Native iOS Components
var RNTWebView = requireNativeComponent('RNTWebView', null);

class WebView extends Component {
  render() {
    return (
      <RNTWebView style={styles.webView} />
    )
  }
}

export default class iOSComponents extends Component {
  componentDidMount() {
    RNTWebView.loadWebsite("http://www.google.com/");
  }
  render() {
    return (
      <View style={styles.webView}>
        <View style={styles.statusBar} />
        <WebView />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  statusBar: {
    height:22,
  },
  webView: {
    flex:1,
  }
});

AppRegistry.registerComponent('iOSComponents', () => iOSComponents);

当我尝试调用 RNTWebView.loadWebsite("http://www.google.com") 时,我收到一条错误消息,指出 RNTWebView.loadWebsite 不是一个函数。

调用本机组件的方式不正确。您可以通过本机模块库调用它。

import { NativeModules } from 'react-native';

// ..rest of your code

// The name of your native module is based on the objective c class name. I assume it to be 'RNTWebViewManager'
let RNTWebView = NativeModules.RNTWebViewManager

// call method
RNTWebView.loadWebsite('https://www.google.com');

更多信息,官方文档是here