react native入门实例分享
1.Hello worldimport React,{ Component } from 'react'; import { AppRegistry,Text } from 'react-native'; class myFirstApp extends Component { render() { return ( <Text>Hello world!</Text> ); } } AppRegistry.registerComponent('myFirstApp',() => myFirstApp); 2.Props(属性)class Greeting extends Component { render() { return ( <View> <Text>Hello {this.props.name}</Text> </View> ); } } export default class myFirstApp extends Component { render() { return ( <View style={{ alignItems: 'center' }}> <Greeting name='react!' /> <Greeting name='react-native' /> <Greeting name='android' /> </View> ) } } 3.State(状态)在constructor中初始化state,然后在需要修改时调用setState方法。 constructor(props){ super(props); this.state = { count: 0,} } doUpdateCount(){ this.setState({ count: this.state.count+1 }) } <Text>当前计数是:{this.state.count}</Text> <TouchableOpacity onPress={this.doUpdateCount.bind(this)} style={{padding: 5,backgroundColor: '#ccc'}}> <Text>点我开始计数</Text> </TouchableOpacity> 4.样式<View> <Text style={[styles.bigblue],{backgroundColor: '#0f0'}}>style set</Text> <Text style={[styles.bigblue,{backgroundColor: '#00f'}]}>style set</Text> <Text style={{color:'#f00'}}>just red</Text> <Text style={styles.red}>just red</Text> <Text style={styles.bigblue}>just bigblue</Text> <Text style={[styles.bigblue,styles.red]}>bigblue,then red</Text> <Text style={[styles.red,styles.bigblue]}>red,then bigblue</Text> </View> const styles = StyleSheet.create({ bigblue: { color: 'blue',fontWeight: 'bold',fontSize: 30,},red: { color: 'red',}); 5.高度与宽度(1)指定宽高 <View> <View style={{width: 50,height: 50,backgroundColor: 'powderblue'}} /> <View style={{width: 100,height: 100,backgroundColor: 'skyblue'}} /> <View style={{width: 150,height: 150,backgroundColor: 'steelblue'}} /> </View> (2)弹性(Flex)宽高 使用flex:1来指定某个组件扩张以撑满所有剩余的空间。如果有多个并列的子组件使用了flex:1,则这些子组件会平分父容器中剩余的空间。如果这些并列的子组件的flex值不一样,则谁的值更大,谁占据剩余空间的比例就更大。 <View style={{flex: 1}}> <View style={{flex: 1,backgroundColor: 'powderblue'}} /> <View style={{flex: 2,backgroundColor: 'skyblue'}} /> <View style={{flex: 3,backgroundColor: 'steelblue'}} /> </View> (3)react native没有宽高100%的设置,所以如果需要让元素撑满屏幕,需要: import { Dimensions,View } from 'react-native'; <View style={{width: Dimensions.get('window').width,height: Dimensions.get('window').height}} /> 6.使用Flexbox布局
<View style={{ flex: 1,flexDirection: 'column',justifyContent: 'center',alignItems: 'center',}}> <View style={{width: 50,backgroundColor: 'powderblue'}} /> <View style={{width: 50,backgroundColor: 'skyblue'}} /> <View style={{width: 50,backgroundColor: 'steelblue'}} /> </View> 7.处理文本输入
constructor(props) { super(props); this.state = {text: ''}; } render() { return ( <View style={{padding: 10}}> <TextInput style={{height: 40}} placeholder="Type here to translate!" onChangeText={(textCont) => this.setState({text:textCont})} /> <Text style={{padding: 10,fontSize: 42}}> {this.state.text.split(' ').map((word) => word && 'xhh').join()} </Text> </View> ); } 8.ScrollViewimport React,{ Component } from 'react'; import { ScrollView,View } from 'react-native'; export default class MyScrollView extends Component { getScrollViewList(){ let scrollViewList = []; let colorList = ['red','green','blue','purple']; for(let i=0;i<colorList.length;i++) { var ViewItem = <View key={i} style={{ width: 420,backgroundColor: colorList[i] }}></View>; scrollViewList.push(ViewItem); } console.log(scrollViewList); return scrollViewList; } render(){ return ( <ScrollView horizontal={true}> { this.getScrollViewList() } </ScrollView> ) } } 如果页面内容一屏展示不完,需要滚动观看那就可以使用 9.ListViewListView组件用于显示一个垂直的滚动列表,其中的元素之间结构近似而仅数据不同。 import React,{ Component } from 'react'; import { ListView,Text,View } from 'react-native'; export class ListViewBasics extends Component { // 初始化模拟数据 constructor(props) { super(props); const ds = new ListView.DataSource({rowHasChanged: (r1,r2) => r1 !== r2}); this.state = { dataSource: ds.cloneWithRows([ 'John','John','James','Jimmy','Jackson','Jillian','Julie','Devin' ]) }; } render() { return ( <View style={{flex: 1,width: 150,marginTop: 5,marginBottom: 5 }}> <ListView dataSource={this.state.dataSource} renderRow={(myRowData) => <Text>{myRowData}</Text>} /> </View> ); } } 10.网络import React,{ Component } from 'react'; import { TouchableOpacity,View } from 'react-native'; export default class FetchAjax extends Component { constructor(){ super(); this.state = { textDesc: 'initialText',} } // 初始化模拟数据 getData(){ fetch('http://facebook.github.io/react-native/movies.json') .then((response) => response.json()) .then((responseJson) => { console.log(responseJson); this.setState({ textDesc: responseJson.movies[0].title,}) }) .catch((error) => { console.error(error); }); } render() { return ( <View> <TouchableOpacity style={{ padding: 5,borderWidth:1,borderColor:'#aaa',borderRadius:4 }} onPress={this.getData.bind(this)} > <Text>Click Get Data</Text> </TouchableOpacity> <Text>{this.state.textDesc}</Text> </View> ); } } 11.路由Navigator导航方法: (route,routeStack) => Navigator.SceneConfigs.FloatFromRight Navigator.SceneConfigs.PushFromRight (默认) Navigator.SceneConfigs.FloatFromRight Navigator.SceneConfigs.FloatFromLeft Navigator.SceneConfigs.FloatFromBottom Navigator.SceneConfigs.FloatFromBottomAndroid Navigator.SceneConfigs.FadeAndroid Navigator.SceneConfigs.HorizontalSwipeJump Navigator.SceneConfigs.HorizontalSwipeJumpFromRight Navigator.SceneConfigs.VerticalUpSwipeJump Navigator.SceneConfigs.VerticalDownSwipeJump
(route,navigator) => <MySceneComponent title={route.title} navigator={navigator} />
index.android.js: configureScene(route){ if(route.name == 'FirstPage'){ return Navigator.SceneConfigs.FloatFromBottom } return Navigator.SceneConfigs.FloatFromRight; } renderScene(router,navigator){ let Component = router.component; switch(router.name){ case "FirstPage": Component = FirstPage; break; case "SecondPage": Component = MySecondPage; break; } return <Component {...router.params} navigator={navigator} /> } renderHead(){ return( <View style={{height:60,position:'absolute',top:0,left:0,right:0,backgroundColor:'#666',borderColor:'#ccc'}}> <Text> {'Navigator Bar'} </Text> </View> ) } <Navigator navigationBar = {this.renderHead()} initialRoute={{name: 'FirstPage'}} configureScene={this.configureScene} renderScene={this.renderScene.bind(this)} /> navigator.js: import React,{ Component } from 'react'; import { Text,View,TouchableOpacity } from 'react-native'; import MySecondPage from './navigatorPage'; export default class FirstPage extends Component { onPressButton() { this.props.navigator.push({ component: MySecondPage,params : { param1 : 'param1Value' },type: 'Bottom' }) console.log(this.props.navigator.getCurrentRoutes()); } componentWillUnmount(){ console.log('FirstPage-componentWillUnmount'); } render(){ return( <View style={{marginTop: 60,flex:1,}}> <Text>{'first Page'}</Text> <TouchableOpacity onPress={()=>this.onPressButton()}> <Text>点击跳转到第二页</Text> </TouchableOpacity> </View> ) } } navigatorPage.js: import React,TouchableOpacity } from 'react-native'; import MyThirdPage from './navigatorOtherPage'; export default class MySecondPage extends Component { onPressButton() { this.props.navigator.push({ component: MyThirdPage,type: 'Right' }) console.log(this.props.param1); //param1Value console.log(this.props.navigator.getCurrentRoutes()); } componentWillUnmount(){ console.log('MySecondPage-componentWillUnmount'); } render(){ return( <View style={{marginTop: 60,}}> <Text>{'second Page'}</Text> <TouchableOpacity onPress={()=>this.onPressButton()}> <Text>点击跳转到第三页</Text> </TouchableOpacity> </View> ) } } navigatorOtherPage.js: import React,TouchableOpacity } from 'react-native'; import FirstPage from './navigator'; import MySecondPage from './navigatorPage'; export default class MyThirdPage extends Component { // <TouchableOpacity onPress={()=>this.props.navigator.pop()}> // <Text>返回到第二页</Text> // </TouchableOpacity> // <TouchableOpacity onPress={()=>this.props.navigator.replace({component: FirstPage})}> // <Text>返回到第一页</Text> // </TouchableOpacity> // 就只执行了一次 // <TouchableOpacity onPress={()=>this.props.navigator.replaceAtIndex({component: FirstPage},2)}> // <Text>返回到第一页</Text> // </TouchableOpacity> // <TouchableOpacity onPress={()=>this.props.navigator.replaceAtIndex({component: MySecondPage},2)}> // <Text>返回到第二页</Text> // </TouchableOpacity> // <TouchableOpacity onPress={()=>this.props.navigator.resetTo({component: FirstPage})}> // <Text>返回到第一页</Text> // </TouchableOpacity> // <TouchableOpacity onPress={()=>this.props.navigator.resetTo({component: MySecondPage})}> // <Text>返回到第二页</Text> // </TouchableOpacity> // <TouchableOpacity onPress={()=>this.props.navigator.popToTop()}> // <Text>返回到第一页</Text> // </TouchableOpacity> componentWillUnmount(){ console.log('MyThirdPage-componentWillUnmount'); } render(){ return( <View style={{marginTop: 60,}}> <Text>{'third Page'}</Text> <TouchableOpacity onPress={()=>this.props.navigator.replace({component: FirstPage})}> <Text>返回到第一页</Text> </TouchableOpacity> </View> ) } } 下面是一个查询用户信息的例子,FirstPage传递id到MySecondPage,然后MySecondPage返回user信息给FirstPage。 import React,{ Component } from 'react'; import { View,Navigator } from 'react-native'; import MySecondPage from './MySecondPage'; export default class FirstPage extends Component { constructor(props) { super(props); this.state = { id: 2,user: null,} } pressButton() { if(this.props.navigator) { this.props.navigator.push({ name: 'MySecondPage',component: MySecondPage,params: { id: this.state.id,//从MySecondPage获取user getUser: (myUser) => { this.setState({ user: myUser }) } } }); } } render() { if(this.state.user) { return( <View> <Text>用户信息: { JSON.stringify(this.state.user) }</Text> </View> ); }else { return( <View> <TouchableOpacity onPress={this.pressButton.bind(this)}> <Text>查询ID为{ this.state.id }的用户信息</Text> </TouchableOpacity> </View> ); } } }
const myObj = { 1: { name: 'user1',age: 25 },2: { name: 'user2',age: 26 } }; import React from 'react'; import { View,Navigator } from 'react-native'; import FirstPage from './FirstPage'; export default class MySecondPage extends React.Component { constructor(props) { super(props); this.state = { id: null } } componentDidMount() { //这里获取从FirstPage传递过来的参数: id this.setState({ id: this.props.id }); } pressButton() { const { navigator } = this.props; if(this.props.getUser) { let user = myObj[this.props.id]; this.props.getUser(user); } if(navigator) { navigator.pop(); } } render() { return( <View> <Text>获得的参数: id={ this.state.id }</Text> <TouchableOpacity onPress={this.pressButton.bind(this)}> <Text>点我跳回去</Text> </TouchableOpacity> </View> ); } } 下面是一个登陆页和欢迎页的例子。
import React,{ Component } from 'react'; import { AppRegistry,Navigator,TouchableOpacity,Platform } from 'react-native'; import Splash from './Splash'; const defaultRoute = { component: Splash }; export default class myFirstApp extends Component { _renderScene(route,navigator) { let Component = route.component; return ( <Component {...route.params} navigator={navigator} /> ); } _renderNavBar() { const styles = { title: { flex: 1,justifyContent: 'center' },button: { flex: 1,width: 50,buttonText: { fontSize: 18,color: '#FFFFFF',fontWeight: '400' } } var routeMapper = { LeftButton(route,navigator,index,navState) { if(index > 0) { return ( <TouchableOpacity onPress={() => navigator.pop()} style={styles.button}> <Text style={styles.buttonText}>Back</Text> </TouchableOpacity> ); } else { return ( <TouchableOpacity onPress={() => navigator.pop()} style={styles.button}> <Text style={styles.buttonText}>Logo</Text> </TouchableOpacity> ); } },RightButton(route,navState) { if(index > 0 && route.rightButton) { return ( <TouchableOpacity onPress={() => navigator.pop()} style={styles.button}> <Text style={styles.buttonText}></Text> </TouchableOpacity> ); } else { return null } },Title(route,navState) { return ( <View style={styles.title}> <Text style={styles.buttonText}>{route.title ? route.title : 'Splash'}</Text> </View> ); } }; return ( <Navigator.NavigationBar style={{ alignItems: 'center',backgroundColor: '#55ACEE',shadowOffset:{ width: 1,height: 0.5,shadowColor: '#55ACEE',shadowOpacity: 0.8,}} routeMapper={routeMapper} /> ) } render() { return ( <View style={{height:200}}> <Navigator initialRoute={defaultRoute} renderScene={this._renderScene} sceneStyle={{paddingTop: (Platform.OS === 'android' ? 66 : 74)}} navigationBar={this._renderNavBar()} /> </View> ); } } }); AppRegistry.registerComponent('myFirstApp',() => myFirstApp);
import React,{ Component } from 'react'; import { View,TouchableOpacity } from 'react-native'; import Login from './Login'; class Splash extends Component { _openPage() { this.props.navigator.push({ title: 'Login',component: Login }) } render() { return ( <View style={{ flex: 1,backgroundColor: '#FFFFFF' }}> <Text>Splash Page</Text> <TouchableOpacity onPress={this._openPage.bind(this)}> <Text style={{ color: '#55ACEE' }}>Open New Page</Text> </TouchableOpacity> </View> ); } } export default Splash;
import React,{ Component } from 'react'; import {View,TextInput,TouchableOpacity } from 'react-native'; import Welcome from './Welcome'; class Login extends Component { constructor(props) { super(props); this.state = { name: null,age: null,} } _openPage() { this.props.navigator.push({ component: Welcome,params: { name: this.state.name,age: this.state.age,changeMyAge: (age) => { this.setState({ age }) } } }) } render() { return ( <View style={{ flex: 1,backgroundColor: '#FFFFFF' }}> <Text>Form Page</Text> <TextInput value={this.state.name} onChangeText={name => this.setState({ name })} placeholder={'Enter your name'} style={{ height: 40,width: 200 }} /> <Text>My age: {this.state.age ? this.state.age : 'Unknown'}</Text> <TouchableOpacity onPress={this._openPage.bind(this)}> <Text style={{ color: '#55ACEE' }}>Update my age</Text> </TouchableOpacity> </View> ); } } export default Login;
import React,{ Component } from 'react'; import { TextInput,TouchableOpacity } from 'react-native'; class Welcome extends Component { _back() { this.props.navigator.pop(); } render() { return ( <View style={{ flex: 1,backgroundColor: '#FFFFFF' }}> <Text>Welcome Page</Text> <Text>Welcome to Navigation! {this.props.name}</Text> <TextInput onChangeText={age => this.props.changeMyAge(age) } placeholder={'Enter your age:'} style={{ height: 40,width: 200 }} /> <TouchableOpacity onPress={this._back.bind(this)}> <Text style={{ color: '#55ACEE' }}>Save my age</Text> </TouchableOpacity> </View> ); } } export default Welcome; 12.组件生命周期实例化 getDefaultProps getInitialState componentWillMount render componentDidMount 实例化完成后的更新 getInitialState componentWillMount render componentDidMount 存在期 componentWillReceiveProps shouldComponentUpdate componentWillUpdate render componentDidUpdate 销毁&清理期 componentWillUnmount 说明 componentWillReceiveProps: function(nextProps) { if (nextProps.bool) { this.setState({ bool: true }); } } 7.shouldComponentUpdate import React,{ Component,PropTypes } from 'react'; import { Text,TouchableOpacity } from 'react-native'; export default class MyPropType extends Component { constructor(props){ super(props); this.state = { stateName: this.props.myName + ',xhh',count: 0,} console.log('init-constructor'); } static propTypes = { myName: PropTypes.string,age: PropTypes.number,sex: PropTypes.string.isRequired } static get defaultProps() { return { myName: "xhh",age: 18 } } doUpdateCount(){ this.setState({ count: this.state.count+1 }) } componentWillMount() { console.log('componentWillMount'); } componentDidMount() { console.log('componentDidMount') } componentWillReceiveProps(nextProps){ console.log('componentWillReceiveProps') } shouldComponentUpdate(nextProps,nextState){ console.log('shouldComponentUpdate'); // return nextProps.id !== this.props.id; if(nextState.count > 10) return false; return true; } componentWillUpdate(){ console.log('componentWillUpdate'); } componentDidUpdate(){ console.log('componentDidUpdate'); } componentWillUnmount(){ console.log('componentWillUnmount'); } render(){ console.log('render'); return ( <View> <Text>姓名:{this.props.myName}</Text> <Text>别名:{this.state.stateName}</Text> <Text>年龄:{this.props.age}</Text> <Text>性别:{this.props.sex}</Text> <Text>父元素计数是:{this.state.count}</Text> <TouchableOpacity onPress={ this.doUpdateCount.bind(this) } style={{ padding: 5,backgroundColor: '#ccc' }}> <Text>点我开始计数</Text> </TouchableOpacity> <SubMyPropType count1={this.state.count} /> </View> ) } } class SubMyPropType extends Component { componentWillReceiveProps(nextProps){ console.log('subMyPropType-componentWillReceiveProps') } shouldComponentUpdate(nextProps,nextState){ console.log('subMyPropType-shouldComponentUpdate'); // return nextProps.id !== this.props.id; if(nextProps.count1 > 5) return false; return true; } componentWillUpdate(){ console.log('subMyPropType-componentWillUpdate'); } componentDidUpdate(){ console.log('subMyPropType-componentDidUpdate'); } componentWillUnmount(){ console.log('subMyPropType-componentWillUnmount'); } render(){ console.log('subMyPropType-render'); return( <Text>子元素计数是:{this.props.count1}</Text> ) } } // init-constructor // componentWillMount // render // subMyPropType-render // componentDidMount //子元素和父元素都在计时 // shouldComponentUpdate // componentWillUpdate // render // subMyPropType-componentWillReceiveProps // subMyPropType-shouldComponentUpdate // subMyPropType-componentWillUpdate // subMyPropType-render // subMyPropType-componentDidUpdate // componentDidUpdate //子元素停止计时(count1 > 5) // shouldComponentUpdate // componentWillUpdate // render // subMyPropType-componentWillReceiveProps // subMyPropType-shouldComponentUpdate // componentDidUpdate //父元素也停止计时 // shouldComponentUpdate // 生命周期 调用次数 能否使用setSate() // getDefaultProps 1(全局调用一次) 否 // getInitialState 1 否 // componentWillMount 1 是 // render >=1 否 // componentDidMount 1 是 // componentWillReceiveProps >=0 是 // shouldComponentUpdate >=0 否 // componentWillUpdate >=0 否 // componentDidUpdate >=0 否 // componentWillUnmount 1 否 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- cocos2d-x v3.x Lua 中 [cc.Layer] 如何不让触摸事件向下转
- c# – 在ViewModel中处理对话框的最佳方法是什么?
- 有没有办法控制C中的结构体之间的填充(包括位域)?
- React Native学习笔记3:导入AndroidStudio及修改项目
- reactjs – React中事件处理程序的奇怪行为
- 收集的sqlite3.7.15.1提供给大家下载(包含jdbc)_windows32位
- flex 学习笔记 正则表达式(二)
- vuex实例详解
- c# – WCF执行错误:此工厂启用了手动寻址,因此必须预先发送
- 在 vb中 end、unload me、exit sub 之间的区别与联系