【问题标题】:Can't find variable: React找不到变量:反应
【发布时间】:2016-12-05 18:23:58
【问题描述】:

我刚开始学习反应,所以如果这听起来像一个愚蠢的问题,我提前道歉。 我正在尝试使用触发操作的按钮制作一个简单的 iOS 页面。 我已按照如何开始的教程进行操作,这是我的索引代码:

'use strict';
var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableHighlight,
  Component,
  AlertIOS // Thanks Kent!
} = React;

class myProj extends Component {
 render() {
    return (
      <View style={styles.container}>
        <Text>
          Welcome to React Native!
        </Text>
        <TouchableHighlight style={styles.button}
            onPress={this.showAlert}>
            <Text style={styles.buttonText}>Go</Text>
          </TouchableHighlight>
      </View>
    );
  }

  showAlert() {
    AlertIOS.alert('Awesome Alert', 'This is my first React Native alert.', [{text: 'Thanks'}] )
  }
}

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFFFFF'
  },
  buttonText: {
    fontSize: 18,
    color: 'white',
    alignSelf: 'center'
  },
  button: {
    height: 44,
    flexDirection: 'row',
    backgroundColor: '#48BBEC',
    alignSelf: 'stretch',
    justifyContent: 'center'
  }
});

AppRegistry.registerComponent('myProj', () => myProj);

问题是当我在我的设备上从 Xcode 运行它时,我得到了

Can't find variable: React
render
main.jsbundle:1509:6
mountComponent
mountChildren

我试图在网上搜索答案,但找不到任何真正有用的东西。知道这里可能是什么问题吗?

【问题讨论】:

  • 尝试使用react-native startreact-native run-ios 命令运行您的项目
  • 我试过了,它显示了同样的错误信息
  • 你的 react-native 版本是什么?

标签: javascript ios react-native


【解决方案1】:

在最新版本的 React Native 中,您必须从“react”包中导入 React

import React, {Component} from 'react';
import {
View,
...
} from 'react-native';

【讨论】:

  • 谢谢!只需在使用 jsx 的地方添加即可
  • @user269867 如果您将应用拆分为 stackNavigator、bottomTabNavigator 等,请检查导航器组件。
  • 我必须在每个文件中都这样做吗?
  • 天哪,谢谢。是的,我认为这确实需要在每个文件中,因为 jsx 只是糖,它的底层依赖于 React 对象
【解决方案2】:
import * as React from 'react';

【讨论】:

  • 天哪,终于解决了那个烦人的错误
【解决方案3】:

在渲染前添加构造函数

constructor(props) {

超级(道具); }

【讨论】:

    猜你喜欢
    • 2021-10-11
    • 2018-12-12
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 2016-08-20
    • 1970-01-01
    • 2022-11-07
    • 1970-01-01
    相关资源
    最近更新 更多