說(shuō)明
- 案例代碼來(lái)自GitChat上李焱的《React Native 移動(dòng)開發(fā)入門與實(shí)戰(zhàn)》(要付費(fèi)的)
- 適用對(duì)象:有一點(diǎn)React/js基礎(chǔ)的
- 使用:你只需要?jiǎng)?chuàng)建新項(xiàng)目徽缚,把下邊代碼直接覆蓋到App.js中即可運(yùn)行柠衍。關(guān)鍵的方法說(shuō)明都在注釋中了姆蘸。
代碼
import React from 'react';
import { StyleSheet, Dimensions,ActivityIndicator, SectionList, FlatList, ScrollView, Alert, Button, Text, View, Image, TextInput} from 'react-native';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
text: '',
isLoading: true,
imgs: [],
};
this.width = Dimensions.get('window').width;
this.height = Dimensions.get('window').height;
}
//生命周期
componentDidMount() {
this.searchHandler();
}
//從百度搜索圖片
/*
ES2017 里的 async/await, 請(qǐng)求的固定寫法:
async function getMoviesFromApi() {
try {
let response = await fetch('https://facebook.github.io/react-native/movies.json');
let responseJson = await response.json();
return responseJson.movies;
} catch(error) {
console.error(error);
}
}
*/
async getImgsFromBaidu(query)
{
try {
//發(fā)送請(qǐng)求
let response = await fetch(`https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&hs=0&xthttps=111111&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=${query}&oq=${query}&rsp=-1`);
//獲取到數(shù)據(jù)
let html = await response.text();
//處理數(shù)據(jù)
const start = "app.setData('imgData', ";
const end = ']}';
const startIndex = html.indexOf(start);
const endIndex = html.indexOf(end, startIndex);
const dataStr = html.slice(startIndex + start.length, endIndex + end.length);
const data = JSON.parse(dataStr.replace(/'/g, '"'));
//返回處理之后的數(shù)據(jù)信息
return data;
} catch (error) {
Alert.alert('getImgsFromBaidu-error:' + error)
console.error(error);
}
}
async searchHandler(query = '漢源湖') {
query = query || '漢源湖';
this.setState({ // 注意平道,如果直接修改 this.state.xxx= xxxx 是不行的撰洗, 不會(huì)渲染頁(yè)面矾屯!
isLoading: true,
});
const imgResult = await this.getImgsFromBaidu(query); //表示等這個(gè)getImgsFromBaidu返回結(jié)果了再繼續(xù)執(zhí)行
// console.log(imgResult); //打印查看數(shù)據(jù)結(jié)構(gòu)
const dataObj = imgResult.data; //根據(jù)'data'得到結(jié)果數(shù)組
console.log(dataObj); //打印查看數(shù)據(jù)結(jié)構(gòu)
const imgsxxx = dataObj.map(e => {
delete e.base64; //刪除base64這個(gè)節(jié)點(diǎn)數(shù)據(jù)
return e;
}).filter(e => !!e.thumbURL);
//套路, !!轉(zhuǎn)boolean +轉(zhuǎn)number ""+ 轉(zhuǎn)string,這里是為了過(guò)濾thumbURL為空的模型,如果為空,則不保留
//filter: 返回值只要是弱等于== true/false
this.setState({
isLoading: false,
imgs: imgsxxx, //相當(dāng)于 開始聲明局部變量和constructor中相同: const imgs= dataObj.map(.... , 然后這里this.setState(...賦值直接寫為 ({isLoading: false, imgs,})
})
}
//按鈕點(diǎn)擊事件
buttonHandler = () => {
this.searchHandler(this.state.text);
}
render() {
return (
<View>
<ScrollView>
<View style={{ height :40}} />
<View>
<View style={{ flex:1, flexDirection: 'row', justifyContent: 'center',}}>
<TextInput style={{width: 300, height: 40, borderColor: 'black', borderWidth: 1,}}
placeholder="漢源湖"
onChangeText={text => this.setState({text})} // 相當(dāng)于: onChangeText={textxxx => this.setState({text: textxxx})},這里是輸入框輸入的結(jié)果賦值給state
/>
<Button
onPress={this.buttonHandler}
title="搜索"
color="#841584"
/>
</View>
</View>
{
//這部分是動(dòng)態(tài)變化的, 如果是刷新狀態(tài)的話,那么就執(zhí)行呈現(xiàn)轉(zhuǎn)圈ActivityIndicator; 如果是刷新完成,那么則顯示FlatList列表
this.state.isLoading ? <ActivityIndicator />
:
<FlatList
data={this.state.imgs}
renderItem={({item}) => {
const img = item;
if(!img.thumbURL) {
return null;
}
return <Image
style={{width: this.width, height: this.width*img.height/img.width}}
source={{uri: img.thumbURL}}
/>
}}
keyExtractor={(item, index) => {
return item.thumbURL;
}}
/>
}
</ScrollView>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
alignItems: 'center',
justifyContent: 'center',
},
});
交流
希望能和大家交流技術(shù)
Blog:http://www.lilongcnc.cc