> 文档中心 > 梅科尔工作室--梁嘉莹-鸿蒙笔记3

梅科尔工作室--梁嘉莹-鸿蒙笔记3

目录

List组件

子组件

接口

语法 

父子组件

组件导出

双向数据绑定

if-else渲染

使用语法

注意事项

for循环渲染

使用语法

注意事项 


List组件

子组件:

Listitem 

接口:

List(value?:{space?: number | string, initialIndex?: number, scroller?: Scroller})

属性 

 

语法 

 

    List({space:20}) { ListItem(){   Text(1)     .fontSize(30).width("100%").height("10%")     .backgroundColor("#FFC0CB").textAlign(TextAlign.Center)     .borderRadius(20) } ListItem(){   Text(2)     .fontSize(30).width("100%").height("10%")     .backgroundColor("#FFC0CB").textAlign(TextAlign.Center)     .borderRadius(20) } ListItem(){   Text(3)     .fontSize(30).width("100%").height("10%")     .backgroundColor("#FFC0CB").textAlign(TextAlign.Center)     .borderRadius(20) }    }

效果如下(上下拉有弹性)

 

在List组件外面用.edgeEffect(EdgeEffect.None) 就可以消除弹性

 

父子组件

父组件:

 

子组件 (自定义组件)

 

 子组件不能直接预览,必须导入父组件才行。

  • 组件导出

子组件导出用export语句

export struct child{

父组件导入用import{子组件文件名称}from "子组件文件相对路径"

import {zidingyi} from "../common/component/child"

  • 双向数据绑定

改变任何一方数据时:两方数据都会变为改变的一方数据

子组件中数据用@Link修饰:

@Link childnum:string

还要把子组件页面里的Text或者其他组件里的值写成  this.childnum

父组件中用@State修饰,在子组件接口中数据用$修饰:

@State fathernum:string = "父组件"

child({childnum:$fathernum})

if-else渲染

使用语法

if/else渲染可以改变组件的渲染状态,即决定组件是否在页面中被渲染,if括号内的变量是true的话,则对应下的组件都被渲染,否则都不被渲染。

if() {    语句}

注意事项

必须在容器组件内使用。

使用if/else可以使子组件的渲染依赖条件语句。

for循环渲染

开发框架提供循环渲染(ForEach组件)来迭代数组,并为每个数组创建相应的组件。

ForEach定义如下:

使用语法

 

@Entry@Componentstruct Index {  @State numlist:number[]= [0,1,2,3,4,5,6,7,8,9]  @State num:number = 1  build() {    Column() {      Text("列表")      .fontSize(30)    List({space:20}) {      ForEach(this.numlist,(item)=>{ ListItem(){   Text(item.toString())  //item是指数组里的数字,toString是把数字转化为字符     .fontSize(30).width("100%").height("10%")     .backgroundColor("#FFC0CB").textAlign(TextAlign.Center)     .borderRadius(20) }      })    }    }    .height('100%').width("100%")    .justifyContent(FlexAlign.Center).alignItems(HorizontalAlign.Center)  }}

注意事项 

必须在容器组件内使用。

生成的子组件允许在ForEach的父容器组件中,允许子组件生成器函数中包含if/else条件渲染,同时也允许ForEach包含在if/else条件渲染语句中;