赞
踩
由list容器组件和listitem容器组件构成,list是一个大容器,listitem是大容器里的小容器
- List(){
- ListItem(){
- }
- }
List( ) { ListItem(){ Text("示例1") .fontSize(30).width("90%").height("10%") } ListItem(){ Text("示例2") fontSize(30).width("90%").height("10%") } ListItem(){ Text("示例3") .fontSize(30) .width("90%").height("10%") } ListItem(){ Text("示例4") .fontSize(30).width("90%").height("10%") } }
子组件在另一个文件夹中新建一个,导出用export语句
父组件调用了子组件,导入用import {子组件文件名称} from "子组件文件相对路径"
改变任何一方数据时,两方数据都会变为改变的一方数据
子组件中数据用@Link修饰
父组件中用@State修饰,在子组件接口中数据用$修饰
使用语法
if/else渲染可以改变组件的渲染状态,即决定组件是否在页面中被渲染。if括号内的变量是true的话,则对应下的组件都被渲染,否则都不被渲染。
注意事项
必须在容器组件内使用。
使用if/else可以使子组件的渲染依赖条件语句。
使用if条件语句:
- Column(){
- if(this.count>0){
- Text('count is positive')
- }}
使用if、else if、else条件语句:
- Column(){
- if(this.count<0){
- Text('count is negative')
- }
- else if(this.count%2===0){
- Divider
- Text('even')
- } else{
- Divider
- Text('odd')
- }
- }
开发框架提供循环渲染(ForEach组件)来迭代数组,并为每个数组项创建相应的组件。ForEach定义如下:
使用语法
- ForEach(
- arr: any[],
- itemGenerator: (item: any, index?: number) => void,
- keyGenerator?: (item: any, index?: number) => string
- )
注意事项
·必须在容器组件内使用;
·生成的子组件允许在ForEach的父容器组件中
·允许子组件生成器函数中包含if/else条件渲染
·同时也允许ForEach包含在if/else条件渲染语句中;
示例
简单类型数组示例:
// xxx.ets @Entry @Component struct MyComponent { @State arr: number[] = [10, 20, 30] build() { Column({ space: 5 }) { Button('Reverse Array') .onClick(() => { this.arr.reverse() }) ForEach(this.arr, (item: number) => { Text(`item value: ${item}`).fontSize(18) Divider().strokeWidth(2) }, (item: number) => item.toString()) } } }
// @ts{child} from "../common/child" @Entry @Component struct Index { @State fathernum: string = '222' @State numlist:number[] = [0,1,2,3,4,5,6,7,8,9] @State num:number=1 build() { Column() { Text("你心目中的男神") .fontSize(40) List({space:20}){ ForEach(this.numlist,(item,index)=>{ ListItem(){ Row() { Text(item.toString()) .fontSize(25).width("100%").height("10%") .backgroundColor("#DCDCDC").textAlign(TextAlign.Center) .borderRadius(25) } } }) } } .width('100%').height('100%') .justifyContent(FlexAlign.Center).alignItems(HorizontalAlign.Center) } }
可滑动,有弹性
@Component export struct child { @Link childnum:number @Link childstatu:boolean build(){ Column({space:10}) { if (this.childstatu) { Text(this.childnum.toString()) .fontSize(30) } Button("增加") .width(100).height(50) .onClick(()=>{ this.childnum++ }) Button("减少") .width(100).height(50) .onClick(()=>{ this.childnum-- }) Button("显示") .width(100).height(50) .onClick(()=>{ this.childstatu =! this.childstatu }) } } }
import {child} from "../common/child" @Entry @Component struct Second{ @State fathernum:number=0 @State fatherstatu:boolean = true build(){ Row(){ Column(){ child({childnum:$fathernum,childstatu:$fatherstatu}) } .width('100%') } .height('100%') } }
点增加数字+1,点减少数字-1,点显示可以切换数字是否显示