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>
)
}
SegmentedView
中 const { 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ā)選中方法。
去 Item
的 constructor()
加入定時(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)在的效果:
