【问题标题】:Custom React Native UI Component: Invariant Violation自定义 React Native UI 组件:Invariant Violation
【发布时间】:2015-10-17 21:14:19
【问题描述】:

我按照文档构建了一个自定义的 React Native UI 组件。这个想法是它将是 Google Maps iOS API 的一个实现,但目前它只是为了显示标准的 Apple 地图。

我使用命令react-native new-library GoogleMapView 构建了一个新模块。这会将所有模块文件添加到/Libraries/GoogleMapView/

我有一个名为 GoogleMapViewManager.h 的文件,其中包含:

#import "RCTViewManager.h"

@interface GoogleMapManager : RCTViewManager

@end

GoogleMapManager.m 文件包含:

#import <MapKit/MapKit.h>
#import "GoogleMapManager.h"

@implementation GoogleMapManager

RCT_EXPORT_MODULE()

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

@end

这显然是根据文档显示地图所需的最低要求。这确实构建并且应用程序启动得很好。

在 JavaScript 方面,我有一个名为 GoogleMapView.js 的文件,其中包含:

'use strict';

var React = require('react-native');
var { requireNativeComponent } = React;

class GoogleMapView extends React.Component {
    render() {
        return <GoogleMap {...this.props} />;
    }
}

GoogleMapView.propTypes = {
    //
};

var GoogleMap = requireNativeComponent('GoogleMap', GoogleMapView);

module.exports = GoogleMapView;

同样,这或多或少是从文档中删除的,所以我希望它能够工作,除非我在某个地方犯了错误。

当我尝试对这个模块做任何事情时,比如将它包含在这样的文件中:

var React = require('react-native'), {Component, View, StyleSheet, GoogleMap} = React;

然后在 JSX 视图中使用它,有点像这样(这是来自我的 Map.js 组件):

render: function() {
    return (
        <View style={styles.flexContainer}>
            <GoogleMap/>
        </View>
    );
}

我收到“不变违规”错误。我不太清楚这意味着什么,完整的堆栈跟踪是这样说的:

localhost:8081/index.ios.bundle
line: 2041
message: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Check the render method of `Map`.'
2015-10-17 22:06:05.289 [warn][tid:com.facebook.React.JavaScript] 'devtools socket closed'

由于无法解决这个问题,我在这里有什么问题吗?

【问题讨论】:

    标签: javascript ios objective-c google-maps react-native


    【解决方案1】:

    JavaScript 要求不正确,我需要使用:

    var GoogleMap = require('../Libraries/GoogleMapView/GoogleMapView.js');
    

    而不是试图将它与 React 要求捆绑在一起:

    var React = require('react-native'), {Component, View, StyleSheet, GoogleMap} = React;
    

    【讨论】:

    • 不错,但为什么呢?对于 React 中的全部内容以及单独的 require 行中的内容是否有规则?
    • 呃。这是我的问题。谢谢。 @zipzit afaik,React 行适用于 React 自己的组件,需要第三方组件。
    猜你喜欢
    • 2020-11-20
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    • 2017-09-16
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多