React native 是facebook开源的移动框架。用JavaScript语言为主,基于React框架。 是适合跨平台移动开发的框架,具有比用webview混合开发更好的性能,又具有h5那样编写一次,跨平台运行的较低维护成本。而且可以和原生很好的结合。
重要特性如下:
如 import, from,class,extends,箭头函数
一般将代码嵌在xml里,但JSX反其道而行之。是将xml嵌在js里。
<View><Text>Hello world!</Text></View>
<View>类似 <div> 或 <span>
</View>
); } }
# 触摸
[ gesture responder system ](https://reactnative.dev/docs/gesture-responder-system)
## 按钮 Button
<Button onPress={() => { alert(‘You tapped the button!’); }} title=”Press Me” />
import React, { Component } from ‘react’; import { Button, StyleSheet, View } from ‘react-native’;
export default class ButtonBasics extends Component { _onPressButton() { alert(‘You tapped the button!’) }
render() { return ( <View style={styles.container}> <View style={styles.buttonContainer}> <Button onPress={this._onPressButton} title=”Press Me” /> </View> <View style={styles.buttonContainer}> <Button onPress={this._onPressButton} title=”Press Me” color=”#841584” /> </View> <View style={styles.alternativeLayoutButtonContainer}> <Button onPress={this._onPressButton} title=”This looks great!” /> <Button onPress={this._onPressButton} title=”OK!” color=”#841584” /> </View> </View> ); } }
const styles = StyleSheet.create({ container: { flex: 1, justifyContent: ‘center’, }, buttonContainer: { margin: 20 }, alternativeLayoutButtonContainer: { margin: 20, flexDirection: ‘row’, justifyContent: ‘space-between’ } });
## 触摸组件 Touchable
自定义触摸效果时使用。
触摸组件 Touchable 可以获取触摸操作的手势,当手势被识别时,可以显示相应的响应。该组件没有提供缺省的样式,所以需要做一点工作以便在app中看起来比较舒畅。
使用哪种触摸组件,取决于需要什么样的反馈。
- TouchableHighlight :任何地方都可使用,如按钮或链接。点击时背景会变暗。
- TouchableNativeFeedback:在 Android 上点击时显示墨水波纹。
- TouchableOpacity 当被按下时,增加透明度反馈,允许背景被看到。
- TouchableWithoutFeedback:只想处理点击,但不需要任何可见的反馈,可以使用它。
import React, { Component } from ‘react’; import { Platform, StyleSheet, Text, TouchableHighlight, TouchableOpacity, TouchableNativeFeedback, TouchableWithoutFeedback, View } from ‘react-native’;
export default class Touchables extends Component { _onPressButton() { alert(‘You tapped the button!’) }
_onLongPressButton() { alert(‘You long-pressed the button!’) }
render() { return ( <View style={styles.container}> <TouchableHighlight onPress={this._onPressButton} underlayColor=”white”> <View style={styles.button}> <Text style={styles.buttonText}>TouchableHighlight</Text> </View> </TouchableHighlight> <TouchableOpacity onPress={this._onPressButton}> <View style={styles.button}> <Text style={styles.buttonText}>TouchableOpacity</Text> </View> </TouchableOpacity> <TouchableNativeFeedback onPress={this._onPressButton} background={Platform.OS === ‘android’ ? TouchableNativeFeedback.SelectableBackground() : ‘’}> <View style={styles.button}> <Text style={styles.buttonText}>TouchableNativeFeedback {Platform.OS !== ‘android’ ? ‘(Android only)’ : ‘’}</Text> </View> </TouchableNativeFeedback> <TouchableWithoutFeedback onPress={this._onPressButton} > <View style={styles.button}> <Text style={styles.buttonText}>TouchableWithoutFeedback</Text> </View> </TouchableWithoutFeedback> <TouchableHighlight onPress={this._onPressButton} onLongPress={this._onLongPressButton} underlayColor=”white”> <View style={styles.button}> <Text style={styles.buttonText}>Touchable with Long Press</Text> </View> </TouchableHighlight> </View> ); } }
const styles = StyleSheet.create({ container: { paddingTop: 60, alignItems: ‘center’ }, button: { marginBottom: 30, width: 260, alignItems: ‘center’, backgroundColor: ‘#2196F3’ }, buttonText: { textAlign: ‘center’, padding: 20, color: ‘white’ } });
# 滚动视界 ScrollView
提供滚动展示和操作,但一次加载全部数据。
import React, { Component } from ‘react’; import { ScrollView, Image, Text } from ‘react-native’;
export default class IScrolledDownAndWhatHappenedNextShockedMe extends Component { render() { return ( <Text style=>Scroll me plz</Text> <Image source= /> <Image source= /> <Image source= /> <Image source= /> <Image source= /> <Text style=>If you like</Text> <Image source= /> <Image source= /> <Image source= /> <Image source= /> <Image source= /> <Text style=>Scrolling down</Text> <Image source= /> <Image source= /> <Image source= /> <Image source= /> <Image source= /> <Text style=>What's the best</Text> <Image source= /> <Image source= /> <Image source= /> <Image source= /> <Image source= /> <Text style=>Framework around?</Text> <Image source= /> <Image source= /> <Image source= /> <Image source= /> <Image source= /> <Text style=>React Native</Text> ); } }
ScrollViews can be configured to allow paging through views using swiping gestures by using the pagingEnabled props. Swiping horizontally between views can also be implemented on Android using the ViewPager component.
On iOS a ScrollView with a single item can be used to allow the user to zoom content. Set up the maximumZoomScale and minimumZoomScale props and your user will be able to use pinch and expand gestures to zoom in and out.
The ScrollView works best to present a small amount of things of a limited size. All the elements and views of a ScrollView are rendered, even if they are not currently shown on the screen. If you have a long list of more items than can fit on the screen, you should use a FlatList instead.
## 平滑列表或分节列表 FlatList 或 SectionList.
The FlatList component displays a scrolling list of changing, but similarly structured, data. FlatList works well for long lists of data, where the number of items might change over time. Unlike the more generic ScrollView, the FlatList only renders elements that are currently showing on the screen, not all the elements at once.
The FlatList component requires two props: data and renderItem. data is the source of information for the list. renderItem takes one item from the source and returns a formatted component to render.
import React, { Component } from ‘react’; import { FlatList, StyleSheet, Text, View } from ‘react-native’;
export default class FlatListBasics extends Component { render() { return ( <View style={styles.container}> <FlatList data={[ {key: ‘Devin’}, {key: ‘Dan’}, {key: ‘Dominic’}, {key: ‘Jackson’}, {key: ‘James’}, {key: ‘Joel’}, {key: ‘John’}, {key: ‘Jillian’}, {key: ‘Jimmy’}, {key: ‘Julie’}, ]} renderItem={({item}) => <Text style={styles.item}>{item.key}</Text>} /> </View> ); } }
const styles = StyleSheet.create({ container: { flex: 1, paddingTop: 22 }, item: { padding: 10, fontSize: 18, height: 44, }, })
If you want to render a set of data broken into logical sections, maybe with section headers, similar to UITableViews on iOS, then a SectionList is the way to go.
import React, { Component } from ‘react’; import { SectionList, StyleSheet, Text, View } from ‘react-native’;
export default class SectionListBasics extends Component { render() { return ( <View style={styles.container}> <SectionList sections={[ {title: ‘D’, data: [‘Devin’, ‘Dan’, ‘Dominic’]}, {title: ‘J’, data: [‘Jackson’, ‘James’, ‘Jillian’, ‘Jimmy’, ‘Joel’, ‘John’, ‘Julie’]}, ]} renderItem={({item}) => <Text style={styles.item}>{item}</Text>} renderSectionHeader={({section}) => <Text style={styles.sectionHeader}>{section.title}</Text>} keyExtractor={(item, index) => index} /> </View> ); } }
const styles = StyleSheet.create({ container: { flex: 1, paddingTop: 22 }, sectionHeader: { paddingTop: 2, paddingLeft: 10, paddingRight: 10, paddingBottom: 2, fontSize: 14, fontWeight: ‘bold’, backgroundColor: ‘rgba(247,247,247,1.0)’, }, item: { padding: 10, fontSize: 18, height: 44, }, })
# 网络
- [ Fetch API ](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)
- [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request)
React Native 提供 Fetch API 满足网络需求。Fetch 和 XMLHttpRequest或其他网络API相似,可以参考 [MDN 指南 Using Fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)
## 同步方式
fetch(‘https://mywebsite.com/endpoint/’, { method: ‘POST’, headers: { Accept: ‘application/json’, ‘Content-Type’: ‘application/json’, }, body: JSON.stringify({ firstParam: ‘yourValue’, secondParam: ‘yourOtherValue’, }), });
## Promise 方式:
function getMoviesFromApiAsync() { return fetch(‘https://reactnative.dev/movies.json’) .then((response) => response.json()) .then((responseJson) => { return responseJson.movies; }) .catch((error) => { console.error(error); }); }
## ES2017 async/await方式
async function getMoviesFromApi() { try { let response = await fetch(‘https://reactnative.dev/movies.json’); let responseJson = await response.json(); return responseJson.movies; } catch (error) { console.error(error); } }
## 处理错误
import React from ‘react’; import { FlatList, ActivityIndicator, Text, View } from ‘react-native’;
export default class FetchExample extends React.Component {
constructor(props){ super(props); this.state ={ isLoading: true} }
componentDidMount(){ return fetch(‘https://reactnative.dev/movies.json’) .then((response) => response.json()) .then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.movies,
}, function(){
});
})
.catch((error) =>{
console.error(error);
}); }
render(){
if(this.state.isLoading){
return(
<View style=>
<ActivityIndicator/>
</View>
)
}
return(
<View style=>
<FlatList
data={this.state.dataSource}
renderItem={({item}) => <Text>{item.title}, {item.releaseYear}</Text>}
keyExtractor={({id}, index) => id}
/>
</View>
); } }
## 其他网络库
XMLHttpRequest API 是 React Native内置的。意味着可以使用依赖它的第三方库如frisbee 或 axios , 或者直接使用 XMLHttpRequest API。
var request = new XMLHttpRequest(); request.onreadystatechange = (e) => { if (request.readyState !== 4) { return; }
if (request.status === 200) { console.log(‘success’, request.responseText); } else { console.warn(‘error’); } };
request.open(‘GET’, ‘https://mywebsite.com/endpoint/’); request.send();
## WebSocket
var ws = new WebSocket(‘ws://host.com/path’);
ws.onopen = () => { // connection opened ws.send(‘something’); // send a message };
ws.onmessage = (e) => { // a message was received console.log(e.data); };
ws.onerror = (e) => { // an error occurred console.log(e.message); };
ws.onclose = (e) => { // connection closed console.log(e.code, e.reason); }; ```
https://reactnative.dev/docs/tutorial
https://facebook.github.io/react/
https://egghead.io/courses/getting-started-with-redux 视频教程
http://www.awesome-react-native.com/ 开源项目