一、父子組件傳參
1、父傳子(@Prop方式)
父組件代碼
@Entry
@Component
struct ParentComponent {@State parentMessage: string = 'Hello from Parent';build() {Column() {ChildComponent({ message: this.parentMessage });}}
}
子組件代碼
@Component
struct ChildComponent {@Prop message: string;build() {Column() {Text(this.message);}}
}
2、父傳子(@Link方式,實現雙向綁定)
父組件代碼
@Entry
@Component
struct ParentComponent {@State parentValue: number = 0;build() {Column() {ChildComponent({ value: $this.parentValue }); // 注意這里使用了$符號,表示傳遞的是引用Text('父組件的值: ' + this.parentValue);}}
}
子組件代碼
@Component
struct ChildComponent {@Link value: number;build() {Column() {Text('子組件的值: ' + this.value);Button('Increase').onClick(() => {this.value += 1; // 修改子組件的值,父組件的值也會同步更新});}}
}
父組件ParentComponent
通過@Link
方式將parentValue
的值傳遞給子組件ChildComponent
,并實現了雙向綁定。當子組件中的按鈕被點擊時,value
的值會增加,同時父組件中的parentValue
也會同步更新。
二、頁面間的傳參(使用router模板)
1、頁面A代碼
import { router } from '@ohos.router';@Entry
@Component
struct PageA {@State dataToSend: string = 'Data from Page A';build() {Column() {Button('Go to Page B').onClick(() => {router.pushUrl({url: 'pages/PageB',params: { message: this.dataToSend }});});}}
}
頁面B代碼
import { router } from '@ohos.router';@Entry
@Component
struct PageB {private receivedMessage: string = '';aboutToAppear() {const params = router.getParams();if (params && params.message) {this.receivedMessage = params.message;}}build() {Column() {Text('Received Message: ' + this.receivedMessage);}}
}
頁面A通過router.pushUrl
方法跳轉到頁面B,并在params參數中傳遞了dataToSend
的值。頁面B在aboutToAppear
生命周期方法中通過router.getParams
方法獲取了這個值,并將其顯示在頁面上。
全局狀態管理(使用裝飾器)
// 定義全局狀態管理器
@Observed
export class GlobalState {userLoggedIn: boolean = false;userName: string = "";
}// 組件A,用于修改全局狀態
@Component
export struct ComponentA {@ObjectLink globalState: GlobalState;build() {Column() {Button("Login").onClick(() => {this.globalState.userLoggedIn = true;this.globalState.userName = "John Doe";});}}
}// 組件B,用于顯示全局狀態
@Component
export struct ComponentB {@Consume globalState: GlobalState;build() {Column() {if (this.globalState.userLoggedIn) {Text("User Logged In: " + this.globalState.userName);} else {Text("User Not Logged In");}}}
}
GlobalState
?類被?@Observed
?裝飾器裝飾,表示它是一個可觀察的全局狀態。ComponentA
?和?ComponentB
?分別使用?@ObjectLink
?和?@Consume
?裝飾器來接收這個全局狀態。當?ComponentA
?修改全局狀態時,ComponentB
?會自動更新顯示內容。
事件總線(Event Bus)
// 定義事件總線
const eventBus = new (function() {this.events = {};this.on = function(eventName, callback) {if (!this.events[eventName]) {this.events[eventName] = [];}this.events[eventName].push(callback);};this.emit = function(eventName, data) {if (this.events[eventName]) {this.events[eventName].forEach(function(callback) {callback(data);});}};
})();// 組件A,用于發送事件
@Component
export struct ComponentA {build() {Button("Send Event").onClick(() => {eventBus.emit("customEvent", { message: "Hello from ComponentA" });});}
}// 組件B,用于接收事件
@Component
export struct ComponentB {message: string = "";constructor() {eventBus.on("customEvent", (data) => {this.message = data.message;});}build() {Text(this.message);}
}
依賴注入(模擬)
// 數據服務組件的工廠類
class DataServiceFactory {static getDataService() {return new DataService();}
}// 數據服務組件
class DataService {getData() {return "Sample Data";}
}// 頁面組件,使用依賴注入獲取數據服務組件
@Component
export struct PageComponent {dataService: DataService;constructor() {this.dataService = DataServiceFactory.getDataService();}build() {Text(this.dataService.getData());}
}
創建了一個?DataServiceFactory
?類來提供?DataService
?的實例。在?PageComponent
?中,我們通過調用?DataServiceFactory.getDataService()
?方法來獲取?DataService
?的實例,并將其存儲在?dataService
?屬性中。然后,我們在?build
?方法中使用這個數據服務來獲取數據并顯示在頁面上。
使用存儲機制(用戶首選項)
import dataPreferences from '@ohos.data.preferences';let context = getContext(this);
let preference: dataPreferences.Preferences;class PreferenceModel {async getPreferencesFromStorage(db_name: string) {try {preference = await dataPreferences.getPreferences(context, db_name);} catch (err) { }}async putData(key: string, data: string, db_name: string = "DB_NAME") {if (!preference) {await this.getPreferencesFromStorage(db_name);}try {await preference.put(key, data);} catch (err) { }await preference.flush();}async getData(key: string, db_name: string = "DB_NAME") {if (!preference) {await this.getPreferencesFromStorage(db_name);}return await preference.get(key, "");}
}const preferenceModel = new PreferenceModel();// 存儲數據
preferenceModel.putData("name", "John Doe");// 讀取數據
preferenceModel.getData("name").then((data) => {console.log("Name: " + data);
});
創建了一個?PreferenceModel
?類來封裝用戶首選項的存儲和讀取操作。我們使用?getPreferencesFromStorage
?方法來獲取用戶首選項的實例,并使用?putData
?和?getData
?方法來存儲和讀取數據。然后,我們使用這些方法來存儲和讀取名為 "name" 的數據。
通過服務進行通信(Service Ability)
// Service Ability 的實現
@Entry
@Service
export class MyService extends Ability {onConnect(intent: Intent): IRemoteObject {return new MyRemoteObject();}
}class MyRemoteObject extends RemoteObject implements IRemoteBroker {onRemoteRequest(code: number, data: MessageParcel, reply: MessageParcel, option: MessageOption): boolean {// 處理來自客戶端的請求let message = data.readString();console.log("Received message from client: " + message);// 回復客戶端reply.writeString("Hello from service!");return true;}
}// 客戶端組件,用于連接和發送消息給 Service Ability
@Component
export struct ClientComponent {build() {Button("Send Message to Service").onClick(() => {let context = getContext() as UIAbilityContext;let intent = new Intent();intent.setElement(new ElementName("com.example.myapplication", "com.example.myapplication.MyService"));context.connectAbility(intent, (err, remoteObject) => {if (err) {console.error("Failed to connect to service: " + err.message);return;}let messageParcel = new MessageParcel();messageParcel.writeString("Hello from client!");remoteObject.sendRequest(1, messageParcel, (reply, option) => {let response = reply.readString();console.log("Received response from service: " + response);});});});}
}
創建了一個?MyService
?類來定義 Service Ability。它實現了?onConnect
?方法來返回一個?MyRemoteObject
?實例,該實例用于處理來自客戶端的請求。客戶端組件?ClientComponent
?使用?connectAbility
?方法連接到 Service Ability,并使用?sendRequest
?方法發送消息給服務。服務接收到消息后,處理消息并回復客戶端。
使用第三方庫或框架提供的傳參機制案例
假設的第三方UI框架:HarmonyUI
1. 安裝和配置第三方庫
首先,確保你的項目已經配置了第三方UI框架?HarmonyUI
。通常這需要在項目的?build.gradle
?文件中添加依賴項。
dependencies {implementation 'com.example:harmonyui:1.0.0'
}
2. 創建兩個組件:
SenderComponent 和 ReceiverComponent
SenderComponent.java
import com.example.harmonyui.Component;
import com.example.harmonyui.communication.DataSender;public class SenderComponent extends Component implements DataSender {private String dataToSend = "Hello, Receiver!";@Overrideprotected void onInit() {super.onInit();// 使用框架提供的API發送數據sendData("receiverId", dataToSend);}// HarmonyUI框架的DataSender接口實現@Overridepublic void sendData(String receiverId, String data) {// 調用框架提供的發送數據方法HarmonyUI.getInstance().sendData(receiverId, data);}
}
ReceiverComponent.java
import com.example.harmonyui.Component;
import com.example.harmonyui.communication.DataReceiver;public class ReceiverComponent extends Component implements DataReceiver {private String receivedData;@Overrideprotected void onInit() {super.onInit();// 注冊接收數據的回調HarmonyUI.getInstance().registerDataReceiver(this, "receiverId");}@Overridepublic void onDataReceived(String data) {this.receivedData = data;// 更新UI或執行其他邏輯updateUI();}private void updateUI() {// 假設有一個顯示數據的文本視圖textView.setText(receivedData);}
}
3、在主應用中注冊和使用這兩個組件
MainApplication.java
import com.example.harmonyui.Application;
import com.example.harmonyui.layout.LinearLayout;public class MainApplication extends Application {@Overrideprotected void onCreate() {super.onCreate();// 創建布局LinearLayout layout = new LinearLayout();// 創建組件實例SenderComponent senderComponent = new SenderComponent();ReceiverComponent receiverComponent = new ReceiverComponent();// 將組件添加到布局中layout.addChild(senderComponent);layout.addChild(receiverComponent);// 設置主布局setMainLayout(layout);}
}
通過上述代碼,SenderComponent
?使用?HarmonyUI
?框架提供的?sendData
?方法將字符串數據發送給?ReceiverComponent
。ReceiverComponent
?通過實現?DataReceiver
?接口并注冊接收數據的回調來接收數據,并在接收到數據后更新UI。
碼字不易,各位網友大佬點點贊唄