【问题标题】:React Native - RCT_EXPORT_VIEW_PROPERTY is nil in view init methodReact Native - RCT_EXPORT_VIEW_PROPERTY 在视图初始化方法中为零
【发布时间】:2017-11-30 21:34:43
【问题描述】:

我正在尝试在 iOS 上的 RN 项目上创建原生 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

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

感谢您的帮助!

【问题讨论】:

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


    【解决方案1】:

    原生 UIView 的 init 方法无法获取 react native 传递的 props。 您应该在属性设置器方法中处理它。

    // 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);
    }
    

    【讨论】:

      猜你喜欢
      • 2022-06-25
      • 2022-11-30
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 2018-11-21
      • 2015-12-11
      • 2023-02-01
      相关资源
      最近更新 更多