react-native開發中常見的問題彙總,如下是我最近在項目開發中遇到的常見的問題,作如下記錄以便後續項目中使用。javascript
componentDidMount () {
NetInfo.addEventListener('change', this.handleConnectivityChange);
}
componentWillUnmount() {
NetInfo.removeEventListener('change', this.handleConnectivityChange);
}
handleConnectivityChange() {
NetInfo.isConnected.fetch().then(netConnected => {
if (netConnected) {
ToastAndroid.show('網絡已鏈接', ToastAndroid.SHORT, ToastAndroid.BOTTOM)
} else {
ToastAndroid.show('請檢查網絡鏈接', ToastAndroid.SHORT, ToastAndroid.BOTTOM)
}
})
}
複製代碼
// navigation 的 didFocus willBlur事件
// BackHandler 的 hardwareBackPress 事件
// this.props.navigation.replace(RouterName) 路由替換
// this.props.navigation.isFocused() 路由激活狀態
_didFocusSubscription;
_willBlurSubscription;
constructor (props) {
super(props)
this._didFocusSubscription = props.navigation.addListener('didFocus', payload =>
BackHandler.addEventListener('hardwareBackPress', this.onBackButtonPressAndroid))
}
componentDidMount () {
this._willBlurSubscription = this.props.navigation.addListener('willBlur', payload => {
BackHandler.removeEventListener('hardwareBackPress', this.onBackButtonPressAndroid)
})
}
componentWillUnmount () {
this._didFocusSubscription && this._didFocusSubscription.remove()
this._willBlurSubscription && this._willBlurSubscription.remove()
BackHandler.removeEventListener('hardwareBackPress', this.onBackButtonPressAndroid)
}
onBackButtonPressAndroid = () => {
if (this.toRouterName) {
this.props.navigation.replace(this.toRouterName)
return true
} else {
return false
}
};
複製代碼
// 須要給TabNavigator 從新傳navigation屬性 從新定義TabNavigator容器組件的router爲TabNavigator的router
class MainView extends Component {
static navigationOptions = {
header: null
};
render () {
let { isMask } = this.props.global
const { cartCount } = this.props
return (
<View> <AppTabNavigator navigation={this.props.navigation}/> </View> ) } } MainView.router = AppTabNavigator.router 複製代碼
navigationOptions: ({navigation, screenProps}) => ({
title: '個人',
tabBarIcon: ({focused}) => (
<Image source={focused ? require('../images/ic_mine_checked.png') : require('../images/ic_mine.png')} style={styles.tabIcon} /> ), tabBarOnPress: () => { if (!screenProps.netConnected) { navigation.navigate('Home') } } }) 複製代碼
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
添加一行:android:screenOrientation="portrait"
設置爲portrait是鎖定豎向,landscape是鎖定橫向
// screenProps tab導航中動態渲染數據 對象中的值能夠綁定redux中的值
<AppTabNavigator screenProps={{cartCount: cartCount}} navigation={this.props.navigation}/>
複製代碼
import { createStackNavigator, NavigationActions } from 'react-navigation'
import { ToastAndroid, BackHandler } from 'react-native'
const AppNavigator = createStackNavigator(routes, stackConfig)const defaultStateAction = AppNavigator.router.getStateForAction
let lastBackPressed = 0
AppNavigator.router.getStateForAction = (action, state) => {
const backRouteName = state && state.routes[state.routes.length - 1].routeName
if (state && (action.type === NavigationActions.BACK) && (backRouteName === 'MainView')) {
if ((lastBackPressed + 2000) < Date.now()) {
ToastAndroid.show('再按一次退出', ToastAndroid.SHORT)
lastBackPressed = Date.now()
return { ...state }
}
BackHandler.exitApp()
}
return defaultStateAction(action, state)
}
複製代碼
import { YellowBox } from 'react-native'
YellowBox.ignoreWarnings(['Warning: isMounted(...) is deprecated', 'Module RCTImageLoader'])
複製代碼
componentWillReceiveProps (nextProps) {
if (!nextProps.xxx) {
dosomething
}
}
shouldComponentUpdate (newProps, newState) {
if (this.props.navigation.isFocused()) {
return true // render
} else {
return false // not render
}
}
複製代碼
import { createStore, applyMiddleware, compose } from 'redux'
import screenTracking from './screenTrackingMiddleware'
import reducer from '../reducers'
import logger from 'redux-logger'
const middlewares = []
if (__DEV__) {
middlewares.push(logger)
}
middlewares.push(screenTracking)
const store = compose(applyMiddleware(...middlewares))(createStore)(reducer)
export default store
複製代碼
react-native-swiper swiper組件
react-native-linear-gradient 漸變組件
react-native-swipe-list-view 側滑組件
react-native-image-crop-picker 圖片裁剪、調用相機和手機相冊
react-native-cookies 管理Cookie
複製代碼
_contentViewScroll (e) {
let offsetY = e.nativeEvent.contentOffset.y // 滑動距離
let contentSizeHeight = e.nativeEvent.contentSize.height // scrollView contentSize高度
let oriageScrollHeight = e.nativeEvent.layoutMeasurement.height // scrollView高度
if (offsetY + oriageScrollHeight >= contentSizeHeight) {
// do something
}
}
<ScrollView
onMomentumScrollEnd={this._contentViewScroll.bind(this)}
showsVerticalScrollIndicator={false}>
</ScrollView>
複製代碼
class ImageAdaptive extends Component {
state = {
width: 0,
height: 0
}
componentDidMount () {
Image.getSize(this.props.uri, (width, height) => {
let h = 330 * height / width
this.setState({height: h})
})
}
render () {
return (
<Image source={{uri: this.props.uri}} style={[{width: 330, height: this.state.height}, this.props.style]} /> ) } } 複製代碼
<Swiper
loop={false}
index={initialSlide}
renderPagination={(index, total) => (
<View style={styles.paginationStyle}> <Text style={styles.paginationText}>{index + 1}/{total}</Text> { delImage ? <TouchableOpacity onPress={() => { delImage && delImage(index) }} style={styles.del}> <Image source={require('../../images/personal/ic_preview_delete.png')} style={styles.imageDel} /> </TouchableOpacity> : null } </View> )}> { images && images.map((image, index) => ( <TouchableOpacity style={styles.imagesItemWrapper} key={index} activeOpacity={1} onPress={this.closeModal}> <Image resizeMode='contain' style={styles.imagesItem} source={{ uri: image }} /> </TouchableOpacity> )) } </Swiper> 複製代碼