HarmonyOS 鸿蒙Next 如何在两个组件之间传递自定义类的数据

HarmonyOS 鸿蒙Next 如何在两个组件之间传递自定义类的数据 源码如下

import UserInfoBean from '../Common/Bean/UserInfoBean';
import { TabID, TabItemList } from '../model/TabItem';
import HomeComponent from '../view/HomeComponent';
import { MineComponent } from '../view/MineComponent';
import { WaterPlanComponent } from '../view/WaterPlanComponent';

[@Component](/user/Component)
struct MainPage {
  public User: UserInfoBean = new UserInfoBean("s", "s", []);
  @State PageIndex: number = 0; //页面索引
  private tabController: TabsController = new TabsController();

  @Builder MyTabBuilder(idx: number){
    Column(){
      Image(idx == this.PageIndex ? TabItemList[idx].icon_selected : TabItemList[idx].icon)
        .width(32)
        .height(32)
      Text(TabItemList[idx].title)
        .fontSize(14)
        .fontWeight(FontWeight.Bold)
        .fontColor(this.PageIndex === idx ? '#006eee':'#888')
    }
  }

  build(){
    Tabs({barPosition:BarPosition.End}){
      TabContent(){
        HomeComponent()
      }
      .tabBar(this.MyTabBuilder(TabID.HOME))

      TabContent(){
        WaterPlanComponent()
      }
      .tabBar(this.MyTabBuilder(TabID.WATER_PLAN))

      TabContent(){
        MineComponent()
      }
      .tabBar(this.MyTabBuilder(TabID.MINE))
    }
    .barWidth('100%')
    .barMode(BarMode.Fixed)
    .width('100%')
    .height('100%')
    .scrollable(true)// 是否可滑动换页
    .onChange((index)=>{
      this.PageIndex = index;
    })
  }
}

其中

HomeComponent()
WaterPlanComponent()
MineComponent()

三个是被@Component定义的组件 在调用的时候没有页面切换

我想传递

public User: UserInfoBean = new UserInfoBean("s", "s", []);

这个类实例的数据给到以上三个组件应该怎么做

希望能得到解答

MineComponent()的源码如下:

import UserInfoBean from '../Common/Bean/UserInfoBean';
import { InfoItem, MineItemList } from '../model/MineItemList';
import router from '@ohos.router';

[@Component](/user/Component)
export struct MineComponent {
  @State nickname: string = 'Jerry'; // 昵称
  @State signature: string = 'nothing to be told';//签名

  build(){
    Column(){
      Column(){
        Text(this.nickname)
          .fontSize(18)
          .fontWeight(FontWeight.Bold)
        Text(this.signature)
          .fontSize(14)
          .fontColor(Color.Orange)
      }
      .width('95%')
      .margin(20)

      //功能列表
      Column(){
        List(){
          ForEach(MineItemList,(item:InfoItem)=>{
            ListItem(){
              Row(){
                Row(){
                  Text(item.title)
                    .fontSize(22)
                    .onClick(()=>{
                      router.pushUrl({
                        url:"../view/MineShow"
                      })
                    })
                }
              }
              .width('100%')
              .height(52)
              .justifyContent(FlexAlign.SpaceBetween)
            }
            .border({
              width:{bottom:1},
              color:Color.Orange
            })

          },item=>JSON.stringify(item))
        }
        .margin(10)
        .border({
          radius:{
            topLeft:24,
            topRight:24
          }
        })
        .backgroundColor('#115f7691')
        .width('100%')
        .height('90%')

      }
      .width('95%')

    }
    .width('100%')
    .height('100%')
    .backgroundColor('#f1f2f3')
  }
}

更多关于HarmonyOS 鸿蒙Next 如何在两个组件之间传递自定义类的数据的实战教程也可以访问 https://www.itying.com/category-93-b0.html

6 回复

我设计了一个方案,通过在两个组件内互相发送emitter来实现通信

https://developer.huawei.com/consumer/cn/blog/topic/03146511351499024

更多关于HarmonyOS 鸿蒙Next 如何在两个组件之间传递自定义类的数据的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


分别在 HomeComponent, WaterPlanComponent, MineComponent 中定义一个类型为 UserInfoBean 的变量。在 MainPage 生成这三个子组件时将 User 传递进去。

如:

HomeComponent({UserObj: this.User})

感谢,回答对我非常有帮助,

您好,有没有什么方法可以使得这样的一个自定义类是可以被全部的组件以及自定义组件访问的?

在HarmonyOS(鸿蒙Next)中,两个组件之间传递自定义类的数据可以通过IntentParcelable接口实现。具体步骤如下:

  1. 定义自定义类:首先,自定义类需要实现Parcelable接口,并重写describeContents()writeToParcel()方法。同时,需要提供一个CREATOR字段来反序列化对象。
import ohos.utils.Parcel;
import ohos.utils.Sequenceable;

public class CustomData implements Sequenceable {
    private String name;
    private int age;

    // 构造函数
    public CustomData(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // 实现Sequenceable接口
    @Override
    public boolean marshalling(Parcel out) {
        out.writeString(name);
        out.writeInt(age);
        return true;
    }

    @Override
    public boolean unmarshalling(Parcel in) {
        name = in.readString();
        age = in.readInt();
        return true;
    }

    // Getter方法
    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public static final Sequenceable.Creator<CustomData> CREATOR = new Sequenceable.Creator<CustomData>() {
        @Override
        public CustomData createFromParcel(Parcel in) {
            return new CustomData(in);
        }

        @Override
        public CustomData[] newArray(int size) {
            return new CustomData[size];
        }
    };

    private CustomData(Parcel in) {
        unmarshalling(in);
    }
}
  1. 发送数据:在发送数据的组件中,创建Intent对象,并使用putSequenceableParam()方法将自定义类对象放入Intent中。
Intent intent = new Intent();
CustomData customData = new CustomData("John", 25);
intent.putSequenceableParam("customData", customData);
startAbility(intent);
  1. 接收数据:在接收数据的组件中,通过IntentgetSequenceableParam()方法获取传递的自定义类对象。
Intent intent = getIntent();
CustomData customData = intent.getSequenceableParam("customData");
if (customData != null) {
    String name = customData.getName();
    int age = customData.getAge();
    // 使用数据
}

通过上述步骤,可以在HarmonyOS中实现两个组件之间传递自定义类的数据。

在HarmonyOS鸿蒙Next中,若要在两个组件之间传递自定义类的数据,可以通过以下步骤实现:

  1. 实现Parcelable接口:自定义类需实现ohos.utils.Parcelable接口,并重写marshallingunmarshalling方法,以便序列化和反序列化对象。

  2. 使用Intent传递:在发送方组件中,将自定义类对象通过IntentsetParam方法放入,然后启动目标组件。

  3. 接收数据:在接收方组件中,通过IntentgetParam方法获取传递的自定义类对象。

确保自定义类的包路径一致,以避免类加载问题。

回到顶部