HarmonyOS鸿蒙Next中TabContent 如何使用自定义文件并传值

HarmonyOS鸿蒙Next中TabContent 如何使用自定义文件并传值

通过Tabs向TabContent中添加 自定义的文件,但是自定义文件只能通过 DocumentRecentlyPage(),而不是通过对象的方式添加属性的方式

@State content:DocumentRecentlyPage = new DocumentRecentlyPage()添加,如果给对应的page中传值

3 回复

参考demo如下:

//index.ets文件
import { TextImage } from './TextImage';

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  @State imageWidth: number = 100;

  build() {
    Column() {
      TextImage({ imageWidth: this.imageWidth })//传imageWidth
    }
    .height('100%')
    .width('100%')
  }
}

//TextImage 文件
@Component
export struct TextImage {
  @Link imageWidth: number;//imageWidth默认大小

  build() {
    Column(){
      Text(this.imageWidth+"")
      Image($r('app.media.app_icon'))
        .width(this.imageWidth)
        .height(100);
    }
  }
}

更多关于HarmonyOS鸿蒙Next中TabContent 如何使用自定义文件并传值的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,TabContent 可以通过自定义文件来实现内容展示,并支持传值。首先,创建一个自定义的ArkTS组件文件,例如 CustomTabContent.ets,在文件中定义组件的UI布局和逻辑。通过 @Component 装饰器声明组件,并在 build 方法中构建UI结构。

接下来,在 TabContent 中使用该自定义组件。通过 TabContentcontent 属性,将自定义组件实例化并传入所需的值。例如:

@Component
struct MyTabs {
  private selectedIndex: number = 0;

  build() {
    Tabs({ barPosition: BarPosition.Start, index: this.selectedIndex }) {
      TabContent() {
        CustomTabContent({ title: "Tab 1", content: "This is Tab 1 content" })
      }.tabBar('Tab 1')

      TabContent() {
        CustomTabContent({ title: "Tab 2", content: "This is Tab 2 content" })
      }.tabBar('Tab 2')
    }
  }
}

@Component
struct CustomTabContent {
  private title: string = "";
  private content: string = "";

  build() {
    Column() {
      Text(this.title)
        .fontSize(20)
        .margin({ bottom: 10 })
      Text(this.content)
        .fontSize(16)
    }
    .padding(10)
  }
}

在上述代码中,CustomTabContent 组件接收 titlecontent 作为参数,并在UI中展示。通过 TabContentcontent 属性,将自定义组件实例化并传入不同的值,实现不同Tab页的内容展示。

在HarmonyOS鸿蒙Next中,TabContent可以通过自定义布局文件并传递参数。首先,创建一个XML布局文件,然后在代码中使用LayoutScatter加载该布局,并通过ComponentContainer添加到TabContent中。传递参数可以通过设置组件的属性或使用Intent。例如:

// 加载自定义布局
Component component = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_custom_tab, null, false);
TabContent tabContent = new TabContent(context);
tabContent.addComponent(component);

// 传递参数
Text text = (Text) component.findComponentById(ResourceTable.Id_text);
text.setText("自定义内容");

这样即可实现自定义布局和传值。

回到顶部