2017-02-13 76 views
1

我有一個場景,其中有兩個組件都使用我編寫的TagInput組件。不幸的是,有很多回調的TagInput需求,爲標籤添加,創建,刪除等,使代碼看起來是這樣的:限制傳遞到React組件

<ComponentOne 
    onTagAdd={this.tagAdd} 
    onTagCreate={this.tagCreate} 
    onTagDelete={this.tagDelete} 
    onTagSetAll={this.tagSetAll} 
/> 

<ComponentTwo 
    onTagAdd={this.tagAdd} 
    onTagCreate={this.tagCreate} 
    onTagDelete={this.tagDelete} 
    onTagSetAll={this.tagSetAll} 
/> 

上的任何其他道具這兩個組件需要的最前端,可能相當於一個很長的名單。

我的問題是,有沒有更好的方法來構造這個?我能想到的唯一的解決辦法是有一個回調,就像這樣:

<ComponentOne 
    onTagAction={this.handleTagAction} 
/> 

<ComponentTwo 
    onTagAction={this.handleTagAction} 
/> 

然後動作和參數傳遞給回調:

handleTagAction = (action, args) => { 
    switch (action) { 
    case 'add': 
     break; 
    case 'create': 
     break; 
    // ... 
    } 
}; 

有沒有更好的辦法,我」米沒有想到?

+0

在哪些情況下應該使用這些元素?我的意思是他們在做同樣的工作,或者他們屬於不同的環境。所以一般來說,關於大圖的任何信息都是有用的。 – Shota

回答

1

你也可以有一個單一的對象,像

const tagActions = { 
    add : this.tagAdd, 
    create : this.tagCreate, 
    delete : this.tagDelete, 
    setAll : this.tagSetAll, 
} 

,然後通過tagActions作爲一個單一的道具你的組件。從你的組件中,你可以調用基於用例的方法,例如this.props.tagActions.add()

相關問題