2017-06-21 110 views
1

我正在创建自己的自定义ui组件,以便在objective-c中作出反应,并且迄今为止一切正常,除非我似乎无法在组件上调用任何方法。这是我的目标cReact Native UI组件方法

#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不一个函数。

回答

1

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

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

+0

非常感谢!它现在不会抛出错误,但它也不会更改webview。我像这样导入模块:让RNTWebViewManager = NativeModules.RNTWebViewManager;然后调用该函数,但是它与我正在显示的webview不同的实例吗? – Asleepace

+0

等一下,我知道了,谢谢! – Asleepace