List组件如何设置多列?

List组件如何设置多列

阅读 1.1k
avatarAI BotBETA

在List组件中设置多列可以通过在列表项的样式中添加flex-wrap: wrap属性来实现。这样可以使得列表项在超出容器宽度时自动换行到下一列。

以下是一个示例代码,演示如何在List组件中设置多列:

<List
  className="list"
  dataSource={dataSource}
  renderItem={renderItem}
>
</List>

const renderItem = (item, index) => {
  return (
    <ListItem
      className="item"
      title={item.title}
      description={item.description}
      style={{
        flexBasis: '33.33%', // 设置列表项的基础宽度为容器宽度的三分之一
        flexWrap: 'wrap', // 设置列表项超出容器宽度时自动换行到下一列
      }}
    />
  );
};

在上述代码中,我们通过在ListItem组件的style属性中添加flex-basis和flex-wrap属性来实现多列布局。其中,flex-basis属性设置列表项的基础宽度为容器宽度的三分之一,而flex-wrap属性设置为wrap,使得列表项在超出容器宽度时自动换行到下一列。

注意,为了让列表项在垂直方向上对齐,可以在List组件的样式中添加alignItems: 'stretch'属性。同时,为了使列表项之间有间隔,可以在样式中添加marginBottom属性。

1 个回答

以列模式为例(listDirection为Axis.Vertical):lanes用于决定List组件在交叉轴方向按几列布局。

示例代码:

@Entry 
@Component 
struct ListLanesExample { 
  @State arr: string[] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19"] 
  @State alignListItem: ListItemAlign = ListItemAlign.Start 
 
  build() { 
    Column() { 
      List({ space: 20, initialIndex: 0 }) { 
        ForEach(this.arr, (item: number) => { 
          ListItem() { 
            Text('' + item) 
              .width('100%') 
              .height(100) 
              .fontSize(16) 
              .textAlign(TextAlign.Center) 
              .borderRadius(10) 
              .backgroundColor(0xFFFFFF) 
          } 
          .border({ width: 2, color: Color.Green }) 
        }) 
      } 
      .height(300) 
      .width("90%") 
      .editMode(true) 
      .border({ width: 3, color: Color.Red }) 
      .lanes({ minLength: 40, maxLength: 40 }) 
      .alignListItem(this.alignListItem) 
 
      Button("点击更改alignListItem:" + this.alignListItem).onClick(() => { 
        if (this.alignListItem == ListItemAlign.Start) { 
          this.alignListItem = ListItemAlign.Center 
        } else if (this.alignListItem == ListItemAlign.Center) { 
          this.alignListItem = ListItemAlign.End 
        } else { 
          this.alignListItem = ListItemAlign.Start 
        } 
      }) 
    }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 }) 
  } 
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进