父子組件之間的交互

問題: 一個組件什么時候放在另一個組件內(nèi)?

比如我有一個 Content 組件,它有2個子組件 ListPlayer。點擊一個 List 元素將加載一個視頻到 Player 中。那么問題來了,是否 Player 組件是否應(yīng)當放在 List 組件當中,他們之間是如何進行交互的?

答案

有一個被大家都接受的架構(gòu)模式稱之為 智能組件和呈現(xiàn)組件(smart component && dumb component).

簡而言之,就本問題來講, ContentComponent 組件將是一個智能組件,它將狀態(tài)和屬性傳遞給它的子組件,即將 videos 傳遞給 ListComponent, 將 chosenVideo(選中的那個視頻)傳遞給 PlayerComponent 組件。我們可以在 ListComponent 組件中通過自定義事件(emit an Event) 來更新 PlayComponent 中播放的視頻

下面代碼示例:

// ContentComponent 父組件
import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';
@Component({
  selector: 'my-content',
  template: `
    <my-list [list]="list | async" (onChosenVideo)="setVideo($event)"></my-list>
    <my-player [video]="chosenVideo"></my-player>
  `
})
export class ContentComponent implements OnInit {
  // 這個組件用于接收外界狀態(tài),即從某個視頻服務(wù)哪里獲取所有的videos
  list: Observable<Video[]>;

  // 這個屬性表示被選中的那個視頻
  chosenVideo: Video;

  constructor(
    private videoService: SomeVideoService // 注入該視頻服務(wù)
  ) {}

  ngOnInit() {
   // 獲取video lists
    this.list = this.videoService.getVideosFromSomeAPISomewhere();
  }

  // 父組件的方法 設(shè)置選中的組件
  setVideo(video: Video) {
    this.chosenVideo = video;
  }
}

// 子組件
// ListComponent
@Component({
  selector: 'my-list',
  template: `
    <ul *ngFor="let video of videos">
      <li (click)="setVideo(video)"> {{ video.title}}</li>
    </ul>
  `
})
export class ListComponent {
  // ListComponent 不關(guān)心視頻數(shù)組從哪里來,它只獲取數(shù)據(jù)即可,即將屬性從別處輸入到這個組件(Input)
  // 這可以認為是組件API的一部分
  // 當別人要使用ListComponent組件時,他的責(zé)任就是堅持上面的原則
  @Input list: Video[];

  // 當使用ListComponent組件時, ListComponent向外輸出一個事件,
  // 這也是ListComponent組件API的一部分

  // 相當于自定義事件, 和父組件進行交互
 @Output() onChoseVideo: EventEmitter = new EventEmitter();

  setVideo(video: Video) {
    this.onChoseVideo.emit(video); // 向外傳遞這個這個值
  }
}

// PlayerComponent
@Component({
  selector: 'my-player',
  template: `
    <div id="player"><!-- your video player html element here --></div>
  `
})
export class PlayerComponent {
  // 這個組件只關(guān)心輸入進來的Video,它不關(guān)心視頻從哪里來
  @Input video: Video;
}

export class Video {
  title: string;
  id: string;
  description: string
}

這篇文章來自 reddit angular2 討論區(qū), 這對父子組件之間的交互講解的十分的透徹,值得反復(fù)的看。

相關(guān)文章:
另外這篇文章講解得很清楚:

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容