• React Native页面props传Boolean值时遇到的问题


    本文写的props传值为跨页面传props,组件嵌套时不会存在这个bug,原因是在没有使用react-router之类的相关组件,而是直接使用原始url跳转的时候会将参数转为字符串

    在RN中自建页面组件(必须是完整页面跳转,例如跳到日历选择页面之类的)时会用到需要传入一个bool值,当希望实现没有传对应的props值时给一个默认值,例如

    MyComponentPage.js

    class MyComponentPage extends React.component {
    	constructor(props) {
    	    super(props);
    	    this.isHandsome = props.isHandsome ? true : false;//通过这行代码实现不传时为false
    	    //this.isHandsome = props.isHandsome || false	//	也可以用这种方式
    	    .... 
    	}
    	....
    }
    

    index.js

    //使用路由跳转到
    <MyComponentPage isHandsome={true}/>
    

    可能初看起来代码没什么问题,但坑就在这里了,在ios设备上这几行代码没有问题,但如果在安卓上,就会遇到一个隐藏的Bug,如果在使用组件时,传了isHandsome={ false }时,会意外的发现到最后组件得到的this.isHandsome的值为true???

    请教大佬后知道,在安卓里,bool值传参是用的String类型!而在js里只要不为空的字符串再判断时都是true!所以这就能解释为什么最后组件得到的this.isHandsome的值为true了,所以在封装的时候应该添加额外的判断:

    MyComponentPage.js

    class MyComponentPage extends React.component {
    	constructor(props) {
    	    super(props);
    		this.isHandsome = props.isHandsome || false;
    		if (typeof this.isHandsome === "string") {
    			this.isHandsome = this.isHandsome == "true" ? true : false;
    		}
    	    .... 
    	}
    	....
    }
    
  • 相关阅读:
    浮起来的验证消息
    关于jQuery UI 使用心得及技巧
    如何制作好一个提交按扭我是个爱折腾的人
    ABAP自测试题一 沧海
    商务出现问题 沧海
    [转帖]Report painter 沧海
    准备ABAP认证 沧海
    Characteristics and Key figures In Report Painter 沧海
    有朋自远方来 沧海
    What are the layers of data description in R/3? 沧海
  • 原文地址:https://www.cnblogs.com/YooHoeh/p/12098883.html
Copyright © 2020-2023  润新知