react native之helloworld
上一篇博客学习了如何在windows下搭建reactnative开发环境,先来简单总结一下吧:
#在终端输入如下命令来安装react-native命令
npm install -g react-native-cli
#同样在终端下输入如下命令来创建react native工程
react-native init 工程名
react-native start
使用谷歌浏览器测试服务是否开启成功,输入: 简单修改作为android开发,先简单修改项目根目录下的index.android.js文件,看下效果: /** * Sample React Native App * https://github.com/facebook/react-native */
'use strict';
var React = require('react-native');
var {
AppRegistry,StyleSheet,Text,View,} = React;
var firstProject = React.createClass({
render: function() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started,edit index.android.js
</Text>
<Text style={styles.instructions}>
Shake or press menu button for dev menu
</Text>
</View>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,justifyContent: 'center',alignItems: 'center',backgroundColor: '#F5FCFF',},welcome: {
fontSize: 20,textAlign: 'center',margin: 10,instructions: {
textAlign: 'center',color: '#333333',marginBottom: 5,});
AppRegistry.registerComponent('firstProject',() => firstProject);
这里我先简单的将欢迎语改为”hello my firstProject”,然后点击menu,或者摇一摇手机,点击”Reload JS”选项,重新加载就可以看到效果了。 简单的数据显示这里我先本地模拟一些数据用来显示。打开index.android.js文件,在该文件中创建如下变量: 模拟简单数据var androidinfo = [
{title: 'android',year: '2016',pic: {thumbnail: 'https://gss1.bdstatic.com/5eN1dDebRNRTm2_p8IuM_a/res/img/logo/logo201509091.png'}},];
这里就是一个javascript数组变量。 声明并赋值需要的变量var { AppRegistry,Image,} = React;
这里声明了五个对象。相当于: var AppRegistry = React.AppRegistry;
var StyleSheet = React.StyleSheet;
var Text = React.Text;
var Image = React.Image;
var View = React.View;
的简写,这里说明一下:
创建需要的样式var styles = StyleSheet.create({ container: { flex: 1,thumbnail: { width: 190,height: 60,});
这里通过React native为我们提供的StyleSheet组件的create方法来创建样式,这个方法不是必须的,但是如果加上的话,其会检查我们的样式代码是否符合react样式规范。 这里定义了两个样式container和thumbnail 添加显示组件var firstProject = React.createClass({ render: function() { // 获取androidinfo数组中的内容 var info = androidinfo[0]; return ( <View style={styles.container}> <Text> {info.title} </Text> <Text> {info.year} </Text> <Image source={{uri: info.pic.thumbnail}} style={styles.thumbnail} /> </View> ); } });
可以看到,这里整个显示的样式是container,通过 完整的代码如下: /** * Sample React Native App * https://github.com/facebook/react-native */
'use strict';
var React = require('react-native');
var androidinfo = [
{title: 'android',];
var {
AppRegistry,} = React;
var firstProject = React.createClass({
render: function() {
var info = androidinfo[0];
return (
<View style={styles.container}>
<Text>
{info.title}
</Text>
<Text>
{info.year}
</Text>
<Image
source={{uri: info.pic.thumbnail}}
style={styles.thumbnail}
/>
</View>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,thumbnail: {
width: 190,() => firstProject);
此时点击menu->reload js,效果如下: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |