React Native (三): 自定義視圖

React Native (一):基礎(chǔ)
React Native (二):StatusBar 冗疮、 NavigationBar 與 TabBar
React Native (三):自定義視圖
React Native (四):加載新聞列表
React Native (五):上下拉刷新加載
React Native (六):加載所有分類與詳情頁(yè)

這次我們要做的仿 新聞?lì)^條 的首頁(yè)的頂部標(biāo)簽列表,不要在意新聞內(nèi)容室抽。

1.請(qǐng)求數(shù)據(jù)

首先做頂部的目錄視圖,首先我們先獲取數(shù)據(jù):

Home.js 中加入方法:

componentDidMount() {
        let url = 'http://api.iapple123.com/newscategory/list/index.html?clientid=1114283782&v=1.1'
        fetch(url, {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
        })
            .then((res) => {
                res.json()
                    .then((json) =>{
                        LOG('GET SUCCESS =>',url, json)

                    })
                    .catch((e) => {
                        LOG('GET ERROR then =>',url,e)

                    })
            })
            .catch((error) => {
                LOG('GET ERROR=>',url, '==>',error)
            })
    }

componentDidMount()是在此頁(yè)面加載完成后由系統(tǒng)調(diào)用。

用到的 LOG 需要在 setup.js 添加全局方法 :

global.LOG = (...args) => {

    if(__DEV__){
        // debug模式
        console.log('/------------------------------\\');
        console.log(...args);
        console.log('\\------------------------------/');
        return args[args.length - 1];
    }else{
        // release模式
    }

};

完整的生命周期可以看這個(gè) 文檔

我們使用 fetch 進(jìn)行請(qǐng)求數(shù)據(jù),你也可以用 這里 的方法進(jìn)行請(qǐng)求數(shù)據(jù)绰垂。

注意在 iOS 中需要去 Xcode 打開(kāi) ATS室奏。

2.自定義視圖

Home 文件夾內(nèi)創(chuàng)建 SegmentedView.js

先定義一個(gè)基礎(chǔ)的 View

import React from 'react'

import {
    View,
    StyleSheet,
    Dimensions
} from 'react-native'
const {width, height} = Dimensions.get('window')

export default class SegmentedView extends React.Component {
    render() {
        const { style } = this.props
        return (
            <View style={[styles.view, style]}>
              
            </View>
        )
    }
}


const styles = StyleSheet.create({
    view: {
        height: 50,
        width: width,
        backgroundColor: 'white',
    }
})

這里的 const {width, height} = Dimensions.get('window') 是獲取到的屏幕的寬和高火焰。

然后在 Home.js 加入 SegmentedView:

import SegmentedView from './SegmentedView'

    render() {
        return (
            <View style={styles.view}>
                <NavigationBar
                    title="首頁(yè)"
                    unLeftImage={true}
                />

                <SegmentedView
                    style={{height: 30}}
                />


            </View>
        )
    }

SegmentedViewconst { style } = this.props 獲取到的就是這里設(shè)置的 style={height: 30}

<View style={[styles.view, style]}> 這樣設(shè)置樣式胧沫,數(shù)組中的每一個(gè)樣式都會(huì)覆蓋它前面的樣式,不過(guò)只會(huì)覆蓋有的 key-value,比如這里 style={height: 30} 称近,它只會(huì)覆蓋掉前面的 height 块攒,最終的樣式為 :

{
    height: 30,
    width: width,
    backgroundColor: 'white',
}
    

3.傳數(shù)據(jù)

請(qǐng)求到的數(shù)據(jù)需要傳給 SegmentedView 來(lái)創(chuàng)建視圖,我們?cè)?Home.js 加入構(gòu)造南蹂,現(xiàn)在的 Home.js 是這樣的:

import React from 'react'

import {
    View,
    StyleSheet
} from 'react-native'

import NavigationBar from '../Custom/NavBarCommon'
import SegmentedView from './SegmentedView'

export default class Home extends React.Component {

    // 構(gòu)造
      constructor(props) {
        super(props);
        // 初始狀態(tài)
        this.state = {
            list: null
        };
      }

    componentDidMount() {
        let url = 'http://api.iapple123.com/newscategory/list/index.html?clientid=1114283782&v=1.1'
        fetch(url, {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
        })
            .then((res) => {
                res.json()
                    .then((json) =>{
                        LOG('GET SUCCESS =>',url, json)

                        this.setState({
                            list: json.CategoryList
                        })
                    })
                    .catch((e) => {
                        LOG('GET ERROR then =>',url,e)
                    })
            })
            .catch((error) => {
                LOG('GET ERROR=>',url, '==>',error)
            })
    }

    render() {
        return (
            <View style={styles.view}>
                <NavigationBar
                    title="首頁(yè)"
                    unLeftImage={true}
                />
                <SegmentedView
                    list={this.state.list}
                    style={{height: 30}}
                />
            </View>
        )
    }
}

const styles = StyleSheet.create({
    view: {
        flex:1,
        backgroundColor: 'white'
    }
})

再數(shù)據(jù)請(qǐng)求完成后調(diào)用 setState() 犬金,系統(tǒng)會(huì)收集需要更改的地方然后刷新頁(yè)面,所以這個(gè)方法永遠(yuǎn)是異步的。

現(xiàn)在請(qǐng)求完數(shù)據(jù)后就會(huì)把數(shù)組傳給 SegmentedView 了晚顷。

再看 SegmentedView 峰伙,我們需要用一個(gè) ScrollView 來(lái)放置這些標(biāo)簽:

import React from 'react'

import {
    View,
    StyleSheet,
    Text,
    TouchableOpacity,
    Dimensions,
    ScrollView
} from 'react-native'

const {width, height} = Dimensions.get('window')


// 一 屏最大數(shù)量, 為了可以居中請(qǐng)?jiān)O(shè)置為 奇數(shù)
const maxItem = 7

export default class SegmentedView extends React.Component {

    // 構(gòu)造
      constructor(props) {
        super(props);
       // 初始狀態(tài)
        this.state = {
            itemHeight: 50,
        };

          if (props.style && props.style.height > 0) {
              this.state = {
                  ...this.state,
                  itemHeight: props.style.height,  //如果在使用的地方設(shè)置了高度,那么保存起來(lái)方便使用
              };
          }
          this._getItems = this._getItems.bind(this)
      }

    _getItems() {
        const { list } = this.props  //獲取到 傳入的數(shù)組

        if (!list || list.length == 0) return []

       // 計(jì)算每個(gè)標(biāo)簽的寬度
        let itemWidth = width / list.length

        if (list.length > maxItem) {
            itemWidth = width / maxItem
        }

        let items = []
        for (let index in list) {
            let dic = list[index]
            items.push(
                <View
                    key={index}
                    style={{height: this.state.itemHeight, width: itemWidth, alignItems: 'center', justifyContent:'center',backgroundColor:'#EEEEEE'}}
                >
                    {/* justifyContent: 主軸居中, alignItems: 次軸居中 */}

                    <Text>{dic.NameCN}</Text>
                </View>
            )
        }

        return items
    }

    render() {
      const { style } = this.props

      return (
            <View style={[styles.view, style]}>
                <ScrollView
                    style={styles.scrollView}
                    horizontal={true} //橫向顯示
                    showsHorizontalScrollIndicator={false} //隱藏橫向滑動(dòng)條
                >
                    {this._getItems()}
                </ScrollView>
            </View>
        )
    }
}


const styles = StyleSheet.create({
    view: {
        height: 50,
        width: width,
        backgroundColor: 'white',
    },

    scrollView: {
        flex:1,
        backgroundColor: '#EEEEEE',
    }
})

4.使標(biāo)簽可選并改變偏移量

現(xiàn)在運(yùn)行已經(jīng)可以顯示出標(biāo)簽列表了,我們還需要能點(diǎn)擊该默,有選中和未選中狀態(tài)瞳氓,所以我們把數(shù)組中添加的視圖封裝一下:


class Item extends React.Component {
    render() {

        const {itemHeight, itemWidth, dic} = this.props

        return (
            <TouchableOpacity
                style={{height: itemHeight, width: itemWidth, alignItems: 'center', justifyContent:'center',backgroundColor:'#EEEEEE'}}
            >
                {/* justifyContent: 主軸居中, alignItems: 次軸居中 */}

                <Text>{dic.NameCN}</Text>
            </TouchableOpacity>
        )
    }
}

我們需要可以點(diǎn)擊,所以把 View 換成了 TouchableOpacity栓袖,記得在頂部導(dǎo)入匣摘。

然后修改數(shù)組的 push 方法


items.push(
    <Item
        key={index}
        itemHeight={this.state.itemHeight}
        itemWidth={itemWidth}
        dic={dic}   
    />
)

現(xiàn)在運(yùn)行已經(jīng)可以點(diǎn)擊了,接下來(lái)設(shè)置選中和未選中樣式裹刮,在 Item 內(nèi)加入:


constructor(props) {
    super(props);
    // 初始狀態(tài)
    this.state = {
        isSelect: false
    };
}

Text 加入樣式:

<Text style={{color: this.state.isSelect ? 'red' : 'black'}}>{dic.NameCN}</Text>

TouchableOpacity 加入點(diǎn)擊事件:

<TouchableOpacity
    style={{height: itemHeight, width: itemWidth, alignItems: 'center', justifyContent:'center',backgroundColor:'#EEEEEE'}}
    onPress={() => {
        this.setState({
            isSelect: true
        })
    }}
>

現(xiàn)在標(biāo)簽已經(jīng)可以進(jìn)行點(diǎn)擊音榜,點(diǎn)擊后變紅,我們需要處理點(diǎn)擊后讓上一個(gè)選中的變?yōu)槲催x中捧弃,我們給 Item 加一個(gè)方法:

_unSelect() {
    this.setState({
        isSelect: false
    })
}

我們還需要接收一個(gè)回調(diào)函數(shù): onPress

const {itemHeight, itemWidth, dic, onPress} = this.props
    
 <TouchableOpacity
    style={{height: itemHeight, width: itemWidth, alignItems: 'center', justifyContent:'center',backgroundColor:'#EEEEEE'}}
    onPress={() => {
        onPress && onPress()
        this.setState({
            isSelect: true
        })
    }}
>

現(xiàn)在去 items.push 加入 onPress 囊咏,我們還需要一個(gè)狀態(tài) selectItem 來(lái)記錄選中的標(biāo)簽:


// 初始狀態(tài)
this.state = {
    itemHeight: 50,
    selectItem: null,
};
<Item
    ref={index}  //設(shè)置 ref 以供獲取自己
    key={index}
    itemHeight={this.state.itemHeight}
    itemWidth={itemWidth}
    dic={dic}
    onPress={() => {
        this.state.selectItem && this.state.selectItem._unSelect() //讓已經(jīng)選中的標(biāo)簽變?yōu)槲催x中
        this.state.selectItem = this.refs[index]  //獲取到點(diǎn)擊的標(biāo)簽
    }}
/>

現(xiàn)在運(yùn)行,就可以選中的時(shí)候取消上一個(gè)標(biāo)簽的選中狀態(tài)了塔橡,但是我們需要默認(rèn)選中第一個(gè)標(biāo)簽梅割。

我們給 Item 加一個(gè)屬性 isSelect

<Item
    ref={index}  //設(shè)置 ref 以供獲取自己
    key={index}
    isSelect={index == 0}
    itemHeight={this.state.itemHeight}
    itemWidth={itemWidth}
    dic={dic}
    onPress={() => {
        this.state.selectItem && this.state.selectItem._unSelect() //讓已經(jīng)選中的標(biāo)簽變?yōu)槲催x中
        this.state.selectItem = this.refs[index]  //獲取到點(diǎn)擊的標(biāo)簽
    }}
/>

修改 Item :

 constructor(props) {
    super(props);
    // 初始狀態(tài)
    this.state = {
        isSelect: props.isSelect
    };
  }
      

現(xiàn)在運(yùn)行發(fā)現(xiàn)第一項(xiàng)已經(jīng)默認(rèn)選中,但是點(diǎn)擊別的標(biāo)簽葛家,發(fā)現(xiàn)第一項(xiàng)并沒(méi)有變成未選中户辞,這是因?yàn)?this.state.selectItem 初始值為 null,那我們需要把第一項(xiàng)標(biāo)簽賦值給它癞谒。

由于只有在視圖加載或更新完成才能通過(guò) refs 獲取到某個(gè)視圖底燎,所以我們需要一個(gè)定時(shí)器去觸發(fā)選中方法。

Itemconstructor() 加入定時(shí)器:

 constructor(props) {
    super(props);
    // 初始狀態(tài)
    this.state = {
        isSelect: props.isSelect
    };
    
    this.timer = setTimeout(
          () => 
              props.isSelect && props.onPress && props.onPress() //100ms 后調(diào)用選中操作
          ,
          100
        ); 
 }
      

搞定弹砚,最后我們還需要點(diǎn)擊靠后的標(biāo)簽可以自動(dòng)居中双仍,我們需要操作 ScrollView 的偏移量,給 ScrollView 設(shè)置 ref='ScrollView'


<ScrollView
    ref="ScrollView"
    style={styles.scrollView}
    horizontal={true}
    showsHorizontalScrollIndicator={false}
>

然后去 items.push 加入偏移量的設(shè)置:

<Item
    ref={index}
    key={index}
    isSelect={index == 0}
    itemHeight={this.state.itemHeight}
    itemWidth={itemWidth}
    dic={dic}
    onPress={() => {
        this.state.selectItem && this.state.selectItem._unSelect()
        this.state.selectItem = this.refs[index]

        if (list.length > maxItem) {
            let meiosis = parseInt(maxItem / 2)
            this.refs.ScrollView.scrollTo({x: (index - meiosis < 0 ? 0 : index - meiosis > list.length - maxItem ? list.length - maxItem : index - meiosis ) * itemWidth, y: 0, animated: true})
        }
    }}
/>

現(xiàn)在的效果:

effect
effect

項(xiàng)目地址

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末桌吃,一起剝皮案震驚了整個(gè)濱河市朱沃,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌茅诱,老刑警劉巖逗物,帶你破解...
    沈念sama閱讀 221,198評(píng)論 6 514
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異瑟俭,居然都是意外死亡翎卓,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,334評(píng)論 3 398
  • 文/潘曉璐 我一進(jìn)店門摆寄,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)失暴,“玉大人坯门,你說(shuō)我怎么就攤上這事《喊牵” “怎么了田盈?”我有些...
    開(kāi)封第一講書(shū)人閱讀 167,643評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)缴阎。 經(jīng)常有香客問(wèn)我允瞧,道長(zhǎng),這世上最難降的妖魔是什么蛮拔? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 59,495評(píng)論 1 296
  • 正文 為了忘掉前任述暂,我火速辦了婚禮,結(jié)果婚禮上建炫,老公的妹妹穿的比我還像新娘畦韭。我一直安慰自己,他們只是感情好肛跌,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,502評(píng)論 6 397
  • 文/花漫 我一把揭開(kāi)白布艺配。 她就那樣靜靜地躺著,像睡著了一般衍慎。 火紅的嫁衣襯著肌膚如雪转唉。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 52,156評(píng)論 1 308
  • 那天稳捆,我揣著相機(jī)與錄音赠法,去河邊找鬼。 笑死乔夯,一個(gè)胖子當(dāng)著我的面吹牛砖织,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播末荐,決...
    沈念sama閱讀 40,743評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼侧纯,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了甲脏?” 一聲冷哼從身側(cè)響起眶熬,我...
    開(kāi)封第一講書(shū)人閱讀 39,659評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎剃幌,沒(méi)想到半個(gè)月后聋涨,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,200評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡负乡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,282評(píng)論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了脊凰。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片抖棘。...
    茶點(diǎn)故事閱讀 40,424評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡茂腥,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出切省,到底是詐尸還是另有隱情最岗,我是刑警寧澤,帶...
    沈念sama閱讀 36,107評(píng)論 5 349
  • 正文 年R本政府宣布朝捆,位于F島的核電站般渡,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏芙盘。R本人自食惡果不足惜驯用,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,789評(píng)論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望儒老。 院中可真熱鬧蝴乔,春花似錦、人聲如沸驮樊。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,264評(píng)論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)囚衔。三九已至挖腰,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間练湿,已是汗流浹背曙聂。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,390評(píng)論 1 271
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留鞠鲜,地道東北人宁脊。 一個(gè)月前我還...
    沈念sama閱讀 48,798評(píng)論 3 376
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像贤姆,于是被迫代替她去往敵國(guó)和親榆苞。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,435評(píng)論 2 359

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