react-native项目经验

修改端口号:node_modules\react-native\local-cli\server\server.js

生成apk:react-native run-android --variant=release

编译项目:react-native  start

  1. 声明样式:var styles=StyleSheet.create({

base:{width:38,height:38},

background:{backgroundColor:’#222’},

active:{borderWidth:2,borderColor:#ccc},

})

  1. CSS的命名“-”连字符改成驼峰写法,长度不加单位“px”,字符串比如色值需要加引号写成字符串。
  2. 标签定义样式:<View style={styles.base}/>

定义多个样式:<View style={[styles.base,styles.background]}/>

在两个样式里面内容有冲突的时候,以右边的值优先,还可以加判断此样式在什么条件下会显示:<View style={[styles.base,this.state.active&&styles.active]}

&&左边是true/false 右边是样式

  1. 隐藏头部:static navigationOptions = () => ({ headerStyle: {display:'none'}})
  2. 跳转页面传参数:<TouchableOpacity style={styles.login} onPress={() => {navigate('Procedure',{ user:'this.state.user', pwd:'this.state.pwd' } );}}> 传参数方法
  3. 自己建的组件名首字母大写
  4. 返回上一级:this.props.navigation.goBack()
  5. 循环组件:{this.state.procedure.map((info, index) => (

<Procedure info={info} key={index}></Procedure>

     ))}

    Procedure为将要循环的数组

  1. 强制刷新:this.forceUpdate();
  2. TextInput只能是数字: keyboardType='numeric'
  3. 点击函数调用接口 函数前加:async  函数名第一个字母大写  调用代码前加:await
  4. 进入页面后做事情:componentDidMount(){   }
  5. 返回页面刷新页面:A页面跳到B页面  B页面返回A页面时  A页面刷新

A页面写:componentDidMount() {

            this.listener = DeviceEventEmitter.addListener('Updata',(e)=>{

              alert(e)

                               这里写需要更新的函数

            });

}

componentWillUnmount(){

  this.listener.remove();

}

         B页面写:DeviceEventEmitter.emit('Updata');

  1. onPress={this.settings.bind(this)}  把控件的this和函数的this绑定成一个this 点击如果加.bind就需要把this传过去
  2. 对齐方式:

a)         justifyContent:'flex-start', // 左对齐,默认值

b)         justifyContent:'flex-end', // 右对齐

c)         justifyContent:'center', // 居中

d)         justifyContent:'space-between', // 两端对齐,项目之间间隔相等 

e)         justifyContent:'space-around', // 每个项目两端的间隔相等。所以项目间的间隔比项目与边框的间隔大一倍

f)          alignItems:'flex-start', // 交叉轴起点对齐

g)         alignItems:'flex-end', // 交叉轴终点对齐

h)         alignItems:'center', // 交叉轴中点对齐

i)           alignItems:'baseline', // 项目第一行文字的基线对齐

j)           alignItems:'stretch', // 如果项目未设置高度或设为auto,将占满整个容器的高度

  1. TextInput 标签:

underlineColorAndroid='transparent'     去掉下划线

  1. 父级页面往自己页面传属性或者值 需要更改父级页面调用时的key值 否则不会刷新

例:<ScanList info={info} key={index+""+this.state.showPop} show={this.state.showPop} navigation={this.props.navigation}/>

  1. 内容横向排列 :flexDirection: 'row',  内容到尾部自动换行:flexWrap:'wrap',
  2. Pda调用扫描:安装DeviceEventEmitter  插件  在文件上面引入:DeviceEventEmitter 

a)         打开扫描:LeZhanTools.openScan(); LeZhanTools.Vibrate(1);

b)         关闭扫描:LeZhanTools.closeScan();

c)         读取扫描出来的信息:DeviceEventEmitter.addListener('ScanCode', function(e: Event) {

d)                                                         alert(JSON.stringify(e)+"222222222")

e)                                              });

  1. ref={(e)=>{this.ModalDropdown2 = e}}  在需要操作这个标签的函数里面写this.ModalDropdown2.select(0)  这样就可以操作这个标签拥有的函数了 
  2. 判断某个元素显示不显示:{this.state.show?null:<Text>这是条件语句</Text>}
  3. 按返回键触发函数:

BackHandler在上面引入。from 'react-native'

componentDidMount() {

this.listenerhardwareBackPress=BackHandler.addEventListener('hardwareBackPress',  ()=> {

           this.backClick();

           return true;

        });

    }

  1. 如果ScrollView标签不能自适应高度  则在最外层标签加 flex:1的样式
  2. 子组件调用父组件函数:父组件:<List back={this.BackClick.bind(this)}></List>

子组件:back(){ this.props.back()}

  1. 点击函数跳转页面:onPress={this.login.bind(this)};login(){const{navigate}= this.props.navigation;navigate('Procedure');}
  2. 禁止重复点击:修改源码 
    位于:../node_modules/react-navigation/src/addNavigationHelper.js 

修改如下:

......

......

export default function<S: {}>(

  navigation: NavigationProp<S>

): NavigationScreenProp<S> {

  /*  ------------此处为添加的代码--------- */

  let debounce = true;//  定义判断变量

  /*  ------------此处为添加的代码--------- */

  return {

    ...navigation,

    goBack: (key?: ?string): boolean => {

      let actualizedKey: ?string = key;

      if (key === undefined && navigation.state.key) {

        invariant(

          typeof navigation.state.key === 'string',

          'key should be a string'

        );

        actualizedKey = navigation.state.key;

      }

      return navigation.dispatch(

        NavigationActions.back({ key: actualizedKey })

      );

    },

    navigate: (

      routeName: string,

      params?: NavigationParams,

      action?: NavigationNavigateAction

  /*  ------------此处为修改后的的代码--------- */

    ): boolean =>{

      if (debounce) {

        debounce = false;

        navigation.dispatch(

          NavigationActions.navigate({

            routeName,

            params,

            action,

          }),

        );

        setTimeout(

          () => {

            debounce = true;

          },

          5000,

        );

        return true;

      }

      return false;

    },

  /*  ------------此处为修改后的的代码--------- */

......

 

 

  1. 横向进出页面:const HelloRN = StackNavigator({

 

},{

  transitionConfig: horizontalInterpolator

})

上面定义:const horizontalInterpolator = () => ({screenInterpolator: CardStackStyleInterpolator.forHorizontal})

import CardStackStyleInterpolator from 'react-navigation/src/views/CardStack/CardStackStyleInterpolator';

 

  1. 文本超出…显示:

{this.state.inner1Con ? (this.state.inner1Con.length > 7 ? this.state.inner1Con.substr(0, 7) + "..." : this.state.inner1Con) : "请选择"}

  1. 虚线:

<View style={styles.lineDashed}></View>

lineDashed:{

     width:width,

     height:0,

     borderWidth:1,

     borderColor:'#ccc',

     borderStyle:'dashed',

borderRadius:0.1,

   },

  1. 左滑删除:

import { Switch,SwipeAction } from 'antd-mobile-rn';

 

const right = [{

        text: '删除',

        onPress: () => alert('delete'),

       style: { backgroundColor: 'red', color: 'white' },

},];

 

<SwipeAction autoClose right={right}>

  <Text>这行左滑删除</Text>

</SwipeAction>

 

  1. 检测设备是否联网

import { NetInfo } from 'react-native';

   //检测网络是否连接

    NetInfo.isConnected.fetch().done((isConnected) => {

      alert(isConnected + '==检测网络是否连接')

    });

 

    //检测网络连接信息

    NetInfo.fetch().done((connectionInfo) => {

      alert(connectionInfo + '==检测网络连接信息')

    });

 

    //监听网络变化事件

    NetInfo.addEventListener('change', (networkType) => {

      alert(networkType + '==监听网络变化事件')

    })

ANT  UI

  1. onClick={() => this.orderClick()}
  2. 列表样式  List标签里面的Item里面的内容 手写没事  如果是动态数据会和之前写死的内容不再一行   解决办法:用Text把内容包起来<Text style={{fontSize:17}}>订单号:{info.con}</Text>

猜你喜欢

转载自www.cnblogs.com/web-lyh/p/10248927.html