React Native - RCT_EXPORT_VIEW_PROPERTY равен нулю в методе инициализации представления
Я пытаюсь создать компонент Native UI в своем проекте RN на iOS. Я передаю реквизит uri
на мой родной компонент. Но когда я пытаюсь использовать его в 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
uri
является nil
в init
но не в onTap
метод, поэтому мне кажется, что мы не можем использовать свойство в методе init? В таком случае, как мне инициализировать мое изображение с этим URI? Есть ли способ узнать, что представление инициализировано? Я думал о создании метода для установки моего изображения и вызова его на части JS в componentDidMount
но он чувствует себя неправильно.
Спасибо за вашу помощь!
1 ответ
Реквизиты, переданные из реакции native, нельзя получить в методе init собственного UIView. Вы должны обработать это в методе установки свойства.
// 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);
}