React Native UI组件方法

时间:2017-06-21 21:45:09

标签: reactjs react-native components native

我正在创建我自己的自定义ui组件,在objective-c中反应原生,到目前为止一切正常,除了我似乎无法调用我的组件上的任何方法。这是我的目标-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(&#34; http://www.google.com&#34;)时,我收到一条错误消息,说RNTWebView.loadWebsite不是函数。

1 个答案:

答案 0 :(得分:1)

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

&#13;
&#13;
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');
&#13;
&#13;
&#13;

有关详细信息,请参阅官方文档here