初識(shí)ReactNative

開發(fā)環(huán)境配置
頁面渲染
  • 組件的渲染需要在自定義 class 中進(jìn)行,每個(gè)自定義視圖class中都包含一個(gè)render()方法,我們需要給render()方法返回一個(gè)自定義組件,由其進(jìn)行將組件渲染:
class MyView extends Component {
    render(){
        return(
            <ScrollView>
                <Text >這里顯示文字</Text>
            </ScrollView>
        );
    }
}
實(shí)現(xiàn)一個(gè)ListView以及下拉刷新
  • 代碼如下:
 class HomeView extends Component {
    constructor(props){
        super(props);
        this.state = {
            dataSource:new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2}),
            loaded:false,
            dataArray:new Array(),
            date:0,
            isRefreshing:false,
        }
    }

    //渲染組件
    render() {
        return(
            <ListView
                style={{flex:1}}
                dataSource={this.state.dataSource}
                renderRow={model=>this.renderRow(model)}
                onEndReached={() => this.fetchData(this.state.date)}
                enableEmptySections={true}
                refreshControl={
                    <RefreshControl
                        refreshing={this.state.isRefreshing}
                        onRefresh={() => this.refreshData()}
                    />
                }
            />
        );
    }

    //組件加載完畢,請(qǐng)求網(wǎng)絡(luò)數(shù)據(jù)
     componentDidMount() {
        this.fetchData(0);
     }
     //開啟網(wǎng)絡(luò)請(qǐng)求
    fetchData(date) {
        var url;
        if (date === 0) {
            url = "http://news-at.zhihu.com/api/4/news/latest";
        }else{
            url = "http://news-at.zhihu.com/api/4/news/before/" + date;
        }
        fetch(url)
            .then((responseData) => responseData.json())
            .then((jsonString) => {
                this.setState({
                    dataArray:this.state.dataArray.concat(jsonString.stories),
                    dataSource:this.state.dataSource.cloneWithRows(this.state.dataArray),
                    date:jsonString.date,
                    loaded:true,
                    isRefreshing:false,
                })
            })
            .done()
    }
    //下拉刷新數(shù)據(jù)
     refreshData() {
        this.state = {
            date:0,
            dataArray:new Array(),
            isRefreshing:true,
            loaded:false,
            dataSource:new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2}),
        };
        this.fetchData(0);
     }
    //返回ListView 的cell
    renderRow(model){
        return(
            <TouchableOpacity style={styles.container} onPress={() => this.didSelectedRow(model)}>
                <Image source={{uri:model.images[0]}} style={styles.imageStyle}/>
                <Text style={styles.titleStyle}>{model.title}</Text>
            </TouchableOpacity>
        );
    }
    //ListView選中某一行之后
     didSelectedRow(model){
        this.props.navigator.push({
            title:model.title,
            component:HomeDetailView,
            passProps:{'newsID':model.id},
        })
    } 
    }
  • 創(chuàng)建樣式
var styles = StyleSheet.create ({
    container:{
        flex:1,
        padding:8,
        height:80,
        flexDirection:'row',
        alignItems:'center',
        justifyContent:'flex-start',
        borderBottomColor:'gray',
        borderBottomWidth:0.4,
    },
    imageStyle:{
        width:100,
        height:70,
    },
    titleStyle:{
        margin:6,
        flex:1,
        fontSize:15,
    }
})
  • 視圖渲染之前會(huì)先執(zhí)行class的構(gòu)造方法,在構(gòu)造方法內(nèi)初始化state參數(shù),為ListView指定dataSource,并指定ListView的刷新狀態(tài)為false,代碼:
onstructor(props){
      super(props);
      this.state = {
          dataSource:new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2}),//指定當(dāng)數(shù)據(jù)不同時(shí)才刷新ListView
          loaded:false,
          dataArray:new Array(), //存儲(chǔ)數(shù)據(jù)model的數(shù)組
          date:0,
          isRefreshing:false,  //ListView下拉刷新初始狀態(tài)
      }
  • 視圖渲染會(huì)調(diào)用render()方法,將ListView生成
render() {
      return(
          <ListView
              style={{flex:1}}
              dataSource={this.state.dataSource}
              renderRow={model=>this.renderRow(model)}
              onEndReached={() => this.fetchData(this.state.date)}
              enableEmptySections={true}
              refreshControl={
                  <RefreshControl    //ListView的下拉刷新控件
                      refreshing={this.state.isRefreshing} 
                      onRefresh={() => this.refreshData()} //刷新時(shí)調(diào)用的方法
                  />
              }
          />
      );
  }
  • 組件已經(jīng)加載完成后會(huì)調(diào)用componentDidMount ()函數(shù),在此方法內(nèi)執(zhí)行網(wǎng)絡(luò)請(qǐng)求:
   componentDidMount() {
      this.fetchData(0);
   }
   //網(wǎng)絡(luò)請(qǐng)求
  fetchData(date) {
      var url;
      if (date === 0) {
          url = "http://news-at.zhihu.com/api/4/news/latest";
      }else{
          url = "http://news-at.zhihu.com/api/4/news/before/" + date;
      }
      fetch(url)
          .then((responseData) => responseData.json())
          .then((jsonString) => {
              this.setState({
                  dataArray:this.state.dataArray.concat(jsonString.stories),//將json解析之后的數(shù)據(jù)數(shù)組交給dataArray
                  dataSource:this.state.dataSource.cloneWithRows(this.state.dataArray),根據(jù)dataArray中的數(shù)據(jù)生成ListView的dataSource
                  date:jsonString.date,
                  loaded:true,
                  isRefreshing:false,//將刷新狀態(tài)置為false
              })
          })
          .done()
  }
  • 組件生命周期
    1. componentWillMount () 這個(gè)函數(shù)調(diào)用時(shí)機(jī)是在組件創(chuàng)建,并初始化了狀態(tài)之后,在第一次繪制 render() 之前。可以在這里做一些業(yè)務(wù)初始化操作,也可以設(shè)置組件狀態(tài)。這個(gè)函數(shù)在整個(gè)生命周期中只被調(diào)用一次
  1. componentDidMount () 在組件第一次繪制完成的回調(diào)函數(shù),通知組件已經(jīng)加載完成
  2. componentWillReceiveProps() 組件的props或state進(jìn)行了修改,組件收到新的屬性
  3. shouldComponentUpdate() 是否更新組件,可以返回false或true來控制是否進(jìn)行渲染
  4. componentWillUpdate()組件將要刷新
  5. componentDidUpdate()組件已經(jīng)完成更新
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • 公司打算用react-native開發(fā)APP,初始RN遇到了很多坑,搭建了一個(gè)小的項(xiàng)目框架,結(jié)合redux根據(jù)公司...
    45b645c5912e閱讀 741評(píng)論 0 5
  • 本人小白,也是最近才開始學(xué)習(xí)ReactNative,只是想記錄自己的學(xué)習(xí)歷程,供日后查閱復(fù)習(xí),文中有任何錯(cuò)誤或者不...
    小唐羽鋒閱讀 1,365評(píng)論 0 51
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,991評(píng)論 19 139
  • 第一次聽到人生關(guān)鍵詞是在古典老師的MVP 課程上,老師讓畫出自己的價(jià)值觀羅盤,我看到那么多關(guān)鍵詞,第一感覺是想我自...
    tianshixiawucha閱讀 1,104評(píng)論 0 0