在使用react-native

时间:2016-12-08 18:20:19

标签: javascript ios xcode react-native jsx

我正在阅读通过Bonnie Eisenman学习React Native ,并且在第3章中遇到WeatherProject教程时出现问题。当应用程序在iOS模拟器中加载时,它似乎正在渲染内容Forecast.js但没有WeatherProject.js的任何内容占用整个显示器

这是我的代码:

index.ios.js

import {
  AppRegistry,
} from 'react-native';

import WeatherProject from './WeatherProject';

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

WeatherProject.js

import React, {
    Component,
} from 'react';

import {
    StyleSheet,
    Text,
    View,
    TextInput,
} from 'react-native';

var Forecast = require('./Forecast');

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#4D4D4D'
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10
  },
  input: {
    fontSize: 20,
    borderWidth: 2,
    height: 40
  }
});

var WeatherProject = React.createClass({

  getInitialState() {
    return {
      zip: '',
      forecast: {
        main: 'Clouds',
        description: 'few clouds',
        temp: 45.7
      }
    }
  },

  _handleTextChange(event) {
    console.log(event.nativeEvent.text);
    this.setState({
      zip: event.nativeEvent.text
    });
  },

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          You input {this.state.zip}.
        </Text>
        <Forecast
          main={this.state.forecast.main}
          description={this.state.forecast.description}
          temp={this.state.forecast.temp}/>
        <TextInput
          style={styles.input}
          returnKeyType="go"
          onSubmitEditing={this._handleTextChange}/>
      </View>
    );
  }
});

module.exports = WeatherProject;

Forecast.js

import React, {
    Component,
} from 'react';

import {
    StyleSheet,
    Text,
    View,
} from 'react-native';

var styles = StyleSheet.create({
  bigText: {
    flex: 2,
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
    color: '#FFFFFF'
  },
  mainText: {
    flex: 1,
    fontSize: 16,
    textAlign: 'center',
    color: '#FFFFFF'
  }
});

var Forecast = React.createClass({

  render() {
    return (
        <View>
          <Text style={styles.bigText}>
            {this.props.main}
          </Text>
          <Text style={styles.mainText}>
            Current conditions: {this.props.description}
          </Text>
          <Text style={styles.bigText}>
            {this.props.temp}°F
          </Text>
        </View>
    );
  }
});

module.exports = Forecast;

预期结果如下(来自书中):

Expected outcome

但我的实际结果是:

Actual outcome

这是视图调试层次结构:

enter image description here

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

在预测中添加此样式:

container: {
  flex: 1,
  justifyContent: 'center',
  alignItems: 'center'
}

然后将样式添加到视图中:

<View styles={style.container}>