ReactNative 踩坑记录

React Native 0.60 及更高版本

在新版本的 React Native 中 链接是自动的(我们不再需要手动的 link 一个 库).
初始化RN项目名称不能使用-来隔开,会报错
Android studio 出现一直在同步Syncing only active variant
File → Settings → Experimental → Gradle → Only sync the active variant 
按着这个设置把Only sync the active variant 打钩去掉即可

总结:Android studio出现问题也可以在Event Log 查找原因。有些只是一些设置的问题。
关于gradle 提示6.0问题

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use ‘–warning-mode all’ to show the individual deprecation warnings.
See https://docs.gradle.org/5.4.1/userguide/command_line_interface.html#sec:command_line_warnings

1.将你的android目录下的build.grade中的signingConfigs 注释掉试一下,重启模拟器可能会好。
2.由于字体图标关系,删除modle,重新npm i  再去settings最后一个关闭什么东西就好了,绿色。
但是不能用。怎么办?
react-native-gestrue-handler一般不会错误,注意字体图标库

0.关于版本:

react-native init demo --verbose --version 0.38.0

0.关于启动屏

有些是android版本
降低版本 react-native init demo --verbose --version 0.59.9

 

can not resolve react-navigation/core导致的报错

重新安装一下 运行命令 npm i @react-navigation/core -S

 

运行react-native run-android 报错 Execution failed for task ':app:compileDebugJavaWithJavac 

仔细看下应该是gradle问题

看着个连接https://blog.youkuaiyun.com/wjj1996825/article/details/79838430

 

reactnavigation2版本和3版本不一样地方:

3.0里面多了一个react-native-gesture-handler手势 来支持滑动 低版本的RN需要link,高版本0.60以上不需要

3.0的里面多了一个createAppContainer包裹 必须用来包裹路由

4.react-navigation-redux-helpers3和以前版本区别:

import {createReactNavigationReduxMiddleware, reduxifyNavigator} from 'react-navigation-redux-helpers';
//改为
import {createReactNavigationReduxMiddleware, createReduxContainer} from 'react-navigation-redux-helpers';
...
export const middleware = createReactNavigationReduxMiddleware(
    'root',
    state => state.nav
);
//改为
export const middleware = createReactNavigationReduxMiddleware(
    state => state.nav,
    'root'
);

5.事件监听:监听手机自带返回键按钮

componentDidMount() {
   BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
}
componentWillUnmount() {
   BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress);
}
handleBackPress = () => {
 //BackHandler.exitApp()  退出

 //this.props.navigation.goBack();返回
    return true;
}

6.配置路由时传参数:(底部导航或者顶部导航)

screen:(props)=><PageTab labeltext='css'/>

7.跳转参数:

NavigatorUtil.GoPage('Detail',{labeltext:this.props.labeltext})
可在detail页面接受参数 
const {navigation}=this.props;  
const {state}=navigation  
const {params}=state;
<Text>{params.labeltext}</Text>

8.躲避键盘遮挡:KeyboardAvoidingView 需要配合ScrollView使用才能避免遮挡,并且点击空白失去光标

<ScrollView
  // contentInsetAdjustmentBehavior="automatic">
   <KeyboardAvoidingView style={{marginTop:300}}
       behavior='padding' 
       keyboardVerticalOffset={150} 这个属性会导致下面的标记距离原位置产生一些变化 150>
    <TextInput style={{
         height:100,width:300,borderWidth:1,
         borderColor:'#666',textAlign:'left',
         textAlignVertical:'top'}} 
         multiline={true} 
         onChangeText={ text => this.text=text}/>
    </KeyboardAvoidingView>
</ScrollView>

9.createSwitchNavigator 路由时跳转:

this.timer=setTimeout(()=>{NavigatorUtil.GoHome(this.props.navigation)},2000)

this.timer&&clearTimeout(this.timer)

10.关于TextInout onChangeText(类似ref用法)

onChangeText={ text => this.text=text}  

11.事件监听:监听手机自带返回键按钮(可以回退编辑,比如说微信发朋友圈,编辑一半,返回会提示你是否保存)

componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBackPressDetail);
  }
componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackPressDetail);
  }
handleBackPressDetail = () => {
    if (this.text) {
      this.setState({showHide:true})
      return true;
    }else{
      this.props.navigation.goBack();
      return true;
    }
  }
  baocun(){
    let that=this;
    AsyncStorage.setItem('text',this.text,function(err){
      if (err) {
        alert('失败');
      }else{
        that.props.navigation.goBack();
      }
    })
  }
  quxiao(){
    this.setState({showHide:false})
    this.props.navigation.goBack();
  }

补充:都看都return true;这是什么?这是真正的触发回退事件条件。其实不建议将数据写到AsyncStorage,因为麻烦,因为后续涉及到一些列的取值,更新,甚至是删除值,建议写到redux里面,这样你的操作增删改查只是action,简化一些。

12 react-native-easy-toast Toast弹窗

import Toast, {DURATION} from 'react-native-easy-toast';
<Toast ref="toast"
       style={{backgroundColor:'#000'}}
       position='top'
       positionValue={400}
       fadeInDuration={750}
       fadeOutDuration={3000}
       opacity={0.8}
       textStyle={{color:'red'}}/>

this.refs.toast.show('toast使用...');

13 ref

ref={reftest=>this.reftest=reftest}   react16以后可以是一个函数  ref={()=> {}}

this.refs.reftest

14 setState();

异步执行,接收两个函数,第一个参数是修改数值,第二个参数是在第一个函数完成后在执行。
如果setState()后执行一个同步函数,例如console,那么console先输出。

15.自定义navbar

https://git.imooc.com/coding-304/GitHub_Advanced/src/master/js/common/NavigationBar.js#L58
import {PropTypes} from 'prop-types';这个直接用吧,安装可能报错。
import NavigatorBar from '../navigator/NavigatorBar';
下面开始都是属性:在NavigatorBar中都可以找到
let statusBar = {
    backgroundColor: this.props.theme,
    barStyle: 'light-content',
};
<NavigatorBar
     statusBar={statusBar}
     hide={false}
     title={'最新'}/>

16.命令:

https://www.jianshu.com/p/eef438821620

17 参考链接:

https://github.com/hopefullman/react-navigator (有redux)

https://github.com/hopefullman/RN (没有redux)

18, DeviceEventEmitter

是如何发送和接收事件的  案例 https://blog.youkuaiyun.com/u011272795/article/details/74832835

19. ParallaxScrollView 

import ParallaxScrollView from 'react-native-parallax-scroll-view';
<ParallaxScrollView
        backgroundColor="#333"
        contentBackgroundColor="pink"
        parallaxHeaderHeight={300}
        stickyHeaderHeight={ 70 }
        backgroundSpeed={10}
        outputScaleValue={10}
        renderStickyHeader={() => (
        <View key="sticky-header" style={{alignItems:'center',
        justifyContent:'center',
        height:70}}>
         <Text style={{color:'#fff'}}>renderStickyHeader</Text>
        </View>
        )}
        renderFixedHeader={() => (
         <View key="sticky-header" style={{position: 'absolute',
         width:width,
         flexDirection:'row',
         alignItems:'center',
         justifyContent:'space-between',
         height:70}}>
         <Text style={{color:'#fff'}} onPress={()=>
           {this.props.navigation.goBack()}}>left</Text>
          <Text style={{color:'#fff'}}>right</Text>
        </View>
        )}
        renderBackground={() => (
          <View key="background">
            <Image source={require('../img/bgf.jpg')} style={{width:width,height:300}}/>
           </View>
        )}
        renderForeground={() => (
         <View style={{height: 300, alignItems: 'center', justifyContent: 'center' }}>
            <Text>Hello World!</Text>
            <Image source={require('../img/bg.jpg')} style={{width:60,
             height:60,
             borderRadius:30}}/>
          </View>
        )}>
        <ScrollView style={{paddingTop:Platform.OS=== 'ios'?0:20}}>
          <Text style={{color:"white"}}>zhelishi1content</Text>
        </ScrollView>
      </ParallaxScrollView>

20.FlatList

<FlatList
          extraData={this.state}
          data={this.state.list}
          keyExtractor={(item) => item.id.toString()}
          ListEmptyComponent={this.ListEmptyComponent()}
          refreshing={this.state.isRefresh}
          onRefresh={() => this._onRefresh_(this.props.labeltext) }
          onEndReached={() => {this.onEndReached(this.props.labeltext)}}
          onEndReachedThreshold={0.4}
          renderItem={({ item }) => <View><Text onPress={ ()=>{ 
            NavigatorUtil.GoPage('Detail',{DetailPageTitle:`${item.id}`}) }}>
            {item.id}
          </Text></View>}/>
存在多次触发 onEndReached 解决办法:最外城100%,每个元素给出高度
<view style={{height:'100%'}}>
<FlatList
          extraData={this.state}
          data={this.state.list}
          keyExtractor={(item) => item.id.toString()}
          ListEmptyComponent={this.ListEmptyComponent()}
          refreshing={this.state.isRefresh}
          onRefresh={() => this._onRefresh_(this.props.labeltext) }
          onEndReached={() => {this.onEndReached(this.props.labeltext)}}
          onEndReachedThreshold={0.4}
          renderItem={({ item }) => <View style={{height:50}}>
          <Text onPress={ ()=>{ NavigatorUtil.GoPage('Detail',
           {DetailPageTitle:`${item.id}`}) }}>{item.id}</Text>
          </View>}/>
</view>

21.启动屏

https://github.com/crazycodeboy/react-native-splash-screen#manual-installation

22.字体图标

npm install --save react-native-vector-icons
有些时候会报错,尝试-save在前面,或者先安装。然后安装其他插件

23.动态创建tabbar

https://github.com/hopefullman/react-navigation-test

24. 集合redux

https://github.com/hopefullman/react-navigator-process

25.更换APP logo

android\app\src\main\res\mipmap-xxxhdpi

26.Android 全面屏

在:android -app-src-AndroidManifest.xml里面的代码中(applycation里面)在 添加
<meta-data
    android:name="android.max_aspect"
    android:value="2.2"
/>

27.关于版本问题,稳定版本

28.关于选择

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
  android:
    'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

 

### React Native 开发常见问题及解决方法 #### 1. 安装依赖问题 当安装新的 UI 库或其他依赖项时,可能会遇到版本不兼容的情况。确保所使用的库版本与当前项目中的其他依赖项相匹配非常重要。对于 `react-native-ui-lib` 和 `React Native Paper` 这样的库,在项目的 `package.json` 文件中确认版本信息可以有效预防此类错误的发生[^1]。 如果检测到版本之间的差异,则应考虑升级至最新的稳定版以保持一致性。可以通过运行命令如: ```bash npm update react-native react-native-paper ``` 或是使用 Yarn 来完成此操作: ```bash yarn upgrade react-native react-native-paper ``` 这有助于减少因不同版本间的API变化而引起的潜在冲突[^2]。 #### 2. 处理日期时间选择器的版本冲突 针对像 `DateTimePicker` 这样特定功能性的组件,在引入新包之前同样需要注意其与其他现有模块是否存在相互作用的问题。特别是要注意检查是否有任何已知的版本冲突报告,并采取相应的措施加以规避或修复[^3]。 #### 3. 寻求外部资源的帮助 即使遵循上述建议,有时仍可能碰到难以自行解决的技术难题。此时查阅官方文档以及活跃于各大技术交流平台上寻求帮助是非常必要的途径之一。许多时候前人已经经历过相同的问题并分享了解决方案,这些都可以成为宝贵的学习资料。 #### 4. 跨平台适配挑战 由于 React Native 的一大特色就是能够编写一次代码同时部署到多个操作系统上,因此不可避免会面临一些关于如何让应用程序在各个目标设备间表现一致性的考验。特别是在处理原生控件样式定制方面尤为明显。熟悉各平台特有的设计指南并将它们融入到应用的设计当中是克服这一障碍的关键所在。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值