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。
