React Native - RCT_EXPORT_VIEW_PROPERTY在视图init方法中为零

时间:2017-11-30 21:34:44

标签: ios objective-c react-native react-native-native-ui-component

我正在尝试在iOS上的RN项目上创建一个Native UI组件。 我将道具uri传递给我的Native组件。但是当我尝试在我的视图的init方法中使用它时,它是nil

// myNativeComponentManager.m

@implementation myNativeComponentManager

RCT_EXPORT_MODULE()
RCT_EXPORT_VIEW_PROPERTY(uri, NSString *);

- (UIView *)view
{
    return [[myNativeComponentView alloc] init];
}

@end

// myNativeComponentView.m

@implementation myNativeComponentView

- (instancetype)init
{
    self = [super init];

// self.uri is nil here
    NSURL *imageURL = [NSURL URLWithString:self.uri];
    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
    UIImage *image = [UIImage imageWithData:imageData];

    self.imgView = [[UIImageView alloc] initWithFrame:self.bounds];
    self.imgView.image = image;
    self.imgView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.imgView.userInteractionEnabled = YES;
    [self addSubview:self.imgView];

    UITapGestureRecognizer *tap =
    [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTap:)];
    [self.imgView addGestureRecognizer:tap];

    return self;
}

- (void)onTap:(id)sender {
// self.uri is not nil here
    NSLog(self.uri);
}
 @end

urinil中是init但在onTap方法中不是componentDidMount所以它让我觉得我们不能在init方法中使用属性?在这种情况下,如何使用此uri初始化我的图像?有没有办法知道视图已初始化?我想过创建一个方法来设置我的图像并在{{1}}的JS部分调用它,但感觉不对。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

从本机UIView的init方法中获取的本地反应原生的

道具无法获取。 你应该在属性setter方法中处理它。

// react native x.js
export default class EmailSSO extends React.Component {
    render() {
        var credential = {
            username: "abc",
            password: "xyz",
        };
        return (
            <EmailView credential={credential} style={{ flex: 1 }} />
        );
    }
}

// native XXXView.m
- (void)setCredential:(Credential *)credential
{
  _credential = credential;
  NSLog(@"Username is %@", credential.username);
}