美文网首页react-nativeReactNative
总结ReactNative一些基础知识

总结ReactNative一些基础知识

作者: Goach | 来源:发表于2018-05-22 17:48 被阅读134次

    关键词

    • let和var的区别
    function test() {
      var a = 1;
      if (true) {
        var a = 2;  // 同样的变量!
        console.log(a);  // 2
      }
      console.log(a);  // 2
    }
    
    function test() {
      let a = 1;
      if (true) {
        let a = 2;  // 不同的变量
        console.log(a);  // 2
      }
      console.log(a);  // 1
    }
    

    var作用于当前申请方法的作用域,let作用于当前申请对象作用域

    • props和state区别

    props由父级设置,它们在组件的整个生命周期中都是固定的。对于将要改变的数据,我们必须使用state

    可以这样说:props指的是物体,state是物体的状态

    样式

    • flex:1

    flex:1 填满剩余空间,类似Android中的layout_weight的属性

    • 实现两个View重叠
    {
      position: 'absolute',
      top: 0,
      left: 0,
      bottom: 0,
      right: 0,
    }
    
    

    组件

    Flexbox

    • flexDirection 布局的主轴
    • justifyContent 布局沿主轴的对齐方式,可用的选项有
      1. flex-start 开始,
      2. center 中间,
      3. flex-end 项目被打包到结束行,物品均匀分布在线上,
      4. space-around 周围有相同的空间,
      5. space-between 中相同的空间间
    • alignItems 布局沿着辅助轴的对齐方式,
      1. start
      2. center
      3. flex-end
      4. stretch 弹性元素被在侧轴方向被拉伸到与容器相同的高度或宽度

    TextInput

    <TextInput
                  style={styles.numberInputStyle}
                  placeholder={'请输入正确的手机号码'}
                  maxLength={11}
                  keybordNumber={'numberic'}
                  onChangeText={(inputNum) => this.setState({inputNum})}
                  />
    

    大概酱紫,具体其他参数可查官网文档

    Image加载图片

     /*<Image source={require('../image/index_phone.png')} style={styles.phone}/>*/
    <Image source={require({item.image})} style={styles.phone}/>//使用错误
    
    

    require的参数不能是变量。

    原因:在打包脚本执行的时候图片路径就已经打包进去,所以不能用变量的形式。

    Text控件水平居中

    Text外面包裹一层View,通过alignItemsjustifyContent实现

    Text组件使用百分比布局会超出手机屏幕宽度

    var dimensions = require('Dimensions');
    var totalWidth = dimensions.get('window').width;
    
    通过totalWidth指定Text组件的宽度!
    
    对于有固定宽度的子组件是支持百分比的,无固定宽度不支持
    

    webView组件

    import React, { Component } from 'react';
    import { WebView } from 'react-native';
    
    class Web extends Component {
      render() {
        const { params } = this.props.navigation.state;
        return (
          <WebView
            source={{uri: params.url}}
          />
        );
      }
    }
    
    module.exports = Web
    

    点击事件

    一个Button的点击事件

    <Button
      onPress={() => {
        Alert.alert('You tapped the button!');
      }}
      title="Press Me"
    />
    
    

    Text组件点击事件也类似,通过onPress实现

    其他控件使用TouchableHighlight(只支持一个子节点)或者TouchableOpacity,Android的波纹效果使用TouchableNativeFeedback,不想要任何效果使用TouchableWithoutFeedback

    关于TouchableHighlightTouchableOpacity区别

    • TouchableHighlight:在TouchableWithoutFeedback的基础上添加了当按下时背景会变暗的效果。
    • TouchableOpacity:相比TouchableHighlight在按下去会使背景变暗的效果,TouchableOpacity会在用户手指按下时降低按钮的透明度,而不会改变背景的颜色。

    注意:

    onPress={this._Handler()}//这样写_Handler方法就执行执行了,因为这样是把_Handler运行完返回的值给onPress了
    
    

    需要这样写

    onPress={()=> this._Handler()}//这种就是把onPress方法赋值给onPress
    

    网络

    • 使用Fetch
    
    fetch('https://mywebsite.com/mydata.json');
    
    
    • POST请求
    
    fetch('https://mywebsite.com/endpoint/', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        firstParam: 'yourValue',
        secondParam: 'yourOtherValue',
      }),
    });
    
    
    • 异步的方式请求
    function getMoviesFromApiAsync() {
      return fetch('https://facebook.github.io/react-native/movies.json')
        .then((response) => response.json())
        .then((responseJson) => {
          return responseJson.movies;
        })
        .catch((error) => {
          console.error(error);
        });
    }
    
    

    也可以使用ES2017的asybc和await的用法

    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);
      }
    }
    
    

    传值

    A页面
    
    onPress={()=>{navigate('Web',{url:'https://www.baidu.com/index.php'})}
    
    
    B页面
    
    const { params } = this.props.navigation.state;
    
    
    params.url//获取方式
    
    

    功能

    • 设置时间延时
     setInterval(() => {
          this.setState(previousState => {
            return { isShowingText: !previousState.isShowingText };
          });
        }, 1000);
    
    
    • 拨打电话
    1. 第一种实现方式通过RN和源生交互,让原生实现
    2. 第二种实现方式,通过RN的Linking提供的方法实现
     //拨打电话  
       linking=(url)=>{  
           console.log(url);  
           Linking.canOpenURL(url).then(supported => {  
               if (!supported) {  
                   console.log('Can\'t handle url: ' + url);  
               } else {  
                   return Linking.openURL(url);  
               }  
           }).catch(err => console.error('An error occurred', err));  
      
        } 
    
    
    1. 通过第三方组件react-native-communications实现,

    第三方组件

    轮播图

    电话,短信,邮件

    下拉选择框

    学习资料

    常用命令

    • npm更新
    npm install -g npm
    
    • 夜神模拟器运行RN配置
    行
    nox_adb shell
    
    在shell环境下执行getprop命令
    
    找到dhcp.eth1.server对应的IP地址
    
    [dhcp.eth1.server]: [172.17.100.2]
    
    打开nox模拟器,确保已经将ReactNative APP安装到模拟器上,
    点击模拟器的摇动按钮,在对话框的DevSettings选项中,填入上面的IP地址和ReactNative默认的8081端口号
    
    • 安装第三方组件
    npm i xxx --save
    
    npm install xxx
    

    学到新知识后续继续更新

    相关文章

      网友评论

        本文标题:总结ReactNative一些基础知识

        本文链接:https://www.haomeiwen.com/subject/bsqkjftx.html