react native组件的创建

react文件加载顺序:

react项目启动后,先加载index.js。在index.js中可以指向首页。

import { AppRegistry } from 'react-native';
import App from './App';

AppRegistry.registerComponent('myExample', () => App);

以上代码中,首页指向了app.js。如果希望指向其他定义的页面,可以这样写

import page from './page ';

AppRegistry.registerComponent('myExample', () => page );

  

一、ES6定义组件(推荐)

1、新建一个myComponent.js。首先引入需要的依赖

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

2、定义组件类,组件需要继承Component ,render()方法里为组件渲染的ui部分,是必须的。

export default class myComponent extends Component {
    render() {
        return (
            <Text>
              Welcome to React Native -androidaa!
            </Text>
        );
      }
} 

3、在需要使用的组件中引入

import MyComponent from './myComponent'
render() {
    return (
        <MyComponent/>
    );
  }

4、如何在es6中使用父组件向子组件传值

子组件使用this.props,用于接收父组件传值

export default class myComponent extends Component {
    render() {
        return (
            <Text>
              Welcome to React Native -androidaa {this.props.name}!
            </Text>
        );
      }
} 

父组件定义属性值

<MyComponent name='小明'/>

二、函数式定义组件(无状态,不能使用this,也没有完整的生命周期方法)

1、定义

function myComponent() {
    return (
        <Text>
            Welcome to React Native -android!
        </Text>
    )
}
module.exports = myComponent

2、如何在函数式里使用父组件向子组件传值 

子组件使用props,用于接收父组件传值

function myComponent(props) {
    return (
        <Text>
            Welcome to React Native -android{props.name}!
        </Text>
    )
}

父组件定义属性值

<MyComponent name='小明'/>

  

如何打开控制台

手机摇一摇,点击remote js debugging。

总结:

1、es6和函数式组件,在父子组件传值时,es6使用this.props.xx,函数式使用props.xx。