【快应用】props属性传值undefined时无法获取默认值

【现象描述】

子组件的props定义属性和默认值,当父组件引用子组件,属性传值undefined时出错。

问题代码如下。

页面hello.ux代码:

<import name="t-item" src="./t-item.ux"></import>
<template>
<div class="" style="width: 100%">
<list style="flex-direction: row;">
<list-item type="test" class="" for="{{list}}">
<t-item class="t-item" item="{{$item}}" width="{{undefined}}" height="{{undefined}}"></t-item>
</list-item>
</list>
</div>
</template>
<script>
export default {
name: '',
data() {
return {
list: [
{ image: 'https://communityfile-drcn.op.hicloud.com/FileServer/getFile/cmtyPub/011/111/111/0000000000011111111.20210630171132.81169860478879908890618042853305:50531229090011:2800:475BAB5A844AF8D249275599DD934CEDB950D2C4E3DBED8D769783BAA4D82BB4.jpg?needInitFileName=true?needInitFileName=true', name: 'HDR MODE' },
{ image: 'https://communityfile-drcn.op.hicloud.com/FileServer/getFile/cmtyPub/011/111/111/0000000000011111111.20191017101406.43002136489534577410716813748735:50531229090011:2800:62F0779EA12370B9DC53B98521A6DC9FF760B266C389A529A7BD515EFF31B249.png?needInitFileName=true?needInitFileName=true?needInitFileName=true?needInitFileName=true', name: 'Night Mode' },
],
};
},
async onInit() {
},
};
</script>
<style lang="less">
</style>

子组件t-item.ux代码:

<template>
<div class="col" style="width: {{width}}px">
<div class="size" style="height: {{height}}px">
<image class="image" src="{{item.image}}" />
</div>
<div class="name">
<text style="lines: 2">{{ item.name }}</text>
</div>
</div>
</template>
<script>
export default {
data() {
return {}
},
props: {
item: {
type: Object,
required: true,
},
width: {
type: Number | String,
default: 298,
},
height: {
type: Number | String,
default: 325,
},
},
onInit() {
console.log("this.width:"+this.width);
console.log("this.height:"+this.height);
},
}
</script>
<style lang="less" >
.image {
width: 100%;
height: 100%;
border-radius: 8px;
object-fit: fill;
}
.name {
margin-top: 10px;
}
.col {
flex-direction: column;
}
</style>

 

【问题分析】

分析如下日志,华为快应用引擎把props传的值“undefined”当做正常的赋值,因此传给图片的宽高不是正确的值,是“undefinedpx”,导致图片无法显示。

08-26 17:14:03.557 I/jsLog (20859): this.width:undefined

08-26 17:14:03.557 I/jsLog (20859): this.height:undefined

 

【解决方法】

如果希望子组件props属性取值为默认值,父组件中可直接不传值,无需进行其他处理,修改代码如下:

<import name="t-item" src="./t-item.ux"></import>
<template>
<div class="" style="width: 100%">
<list style="flex-direction: row;">
<list-item type="test" class="" for="{{list}}">
<t-item class="t-item" item="{{$item}}"></t-item>
</list-item>
</list>
</div>
</template>

 欲了解更多更全技术文章,欢迎访问https://developer.huawei.com/consumer/cn/forum/?ha_source=zzh​

posted @ 2023-02-22 09:50  华为开发者论坛  阅读(28)  评论(0编辑  收藏  举报