React-Native: 如何从React-Native视图返回到原生视图?

10

我正在将React-Native集成到我的现有应用程序中的一部分,但是我遇到了困难,不知道如何“退出”React-Native并返回到本地视图。

以下是一些代码:

// Main objective-c code that bootstraps the react-native view. This view is loaded as a modal view.
MainViewController.m:

- (void)viewDidLoad {
    [super viewDidLoad];

    RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"IndexApp" initialProperties:props launchOptions:nil];

    rootView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height-49);
    [self.view addSubview:rootView];

}

我的初始React观点如下:

render() {
  return (
      <Navigator
          style={styles.container}
...

我在导航器上有一个右侧导航按钮,我想要“解散”react视图和底层的MainViewController本地视图。

我尝试使用从react视图回调到MainViewController的方式,但未成功:

RCT_EXPORT_METHOD(dismiss:(NSString *)name location:(NSString *)location)
{
    NSLog(@"dismiss...");
    // these don't do anything
    //[self dismissViewControllerAnimated:YES completion:nil];
    //[self.navigationController popViewControllerAnimated:YES];
    // anything with _rootView doesn't do anything, i.e. _rootView removeFromSuperview];

}

如果您需要一种方法“退出”React Native视图并返回到本地视图,我们可以提供帮助。


我已经尝试了一个回调到MainViewController,你是怎么做到的? - nr5
3个回答

3

我发现这种方法是有效的(点击链接查看)

其主要内容如下:

  1. 创建一个Obj-C NotificationManager类,并将其公开为React Module。
  2. 在ViewController中注册一个通知,当接收到该通知时会触发[self dismissViewController..]。

完美运作!我在想,因为已经过去4年了,是否有一些更新、更简单/更酷的方法来完成同样的事情? - chamcham

1

你需要在主线程上运行pop或dismiss操作:

RCT_EXPORT_METHOD(dismiss:(NSString *)name location:(NSString *)location)
{
    NSLog(@"dismiss...");
    dispatch_async(dispatch_get_main_queue(), ^{
        [self dismissViewControllerAnimated:YES completion:nil];

        // use pop instead if this view controller was pushed onto a navigation controller
        //[self.navigationController popViewControllerAnimated:YES];
    }
}

请问您能否指导我如何将您的类和方法暴露给React Native模块? - nr5

0

注意:这个方法不起作用 - 我把它留在这里只是为了说明什么不起作用。请查看我的其他答案,以获取可行的方法。

如果您以这种方式呈现MainViewController,则popViewController:应该可以工作。

NSURL *jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios&dev=true"];
RCTRootView *reactView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                    moduleName:@"SimpleApp"
                                             initialProperties:nil
                                                 launchOptions:nil];


MainViewController *rootViewController = [MainViewController new];
rootViewController.view = reactView;

[[self navigationController] pushViewController:rootViewController animated:YES];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接