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;
		}
	    .... 
	}
	....
}
posted @ 2019-06-21 09:50  YooHoeh  阅读(232)  评论(0编辑  收藏  举报
被你发现了?