2016-08-10 26 views
0

所以我正在嘗試爲我將在我的網站上重複使用的不同部分創建一種抽象「框架」。React - 將組件功能暴露給其子女

所以現在我工作的一個模式,其中包括:

  • 冠軍
  • 其內容
  • 操作(按鍵喜歡取消,保存等)

我想如何寫它將是:

<Modal> // <- This wrapper contains different functions for controlling the entire modal. 
    <ModalTitle>Editing</ModalTitle> 
    <ModalContent> 
    <form> 
     <input type="text"/> 
    </form> 
    </ModalContent> 
    <ModalActions/> // <- This one is empty since I already have save buttons as a default for it. 
</Modal> 

這將讓我改變的內容,標題和每個模態添加特定的動作,下面是不同部分的一些代碼:

var Modal = React.createClass({ 
    close: function() { 
    this.props.onUserClose(); 
    }, 
    save: function() { 
    // validates inputs from a form, sends it back, and closes the modal 
    }, 
    render: function() { 
    return (
     <dialog className="mdl-dialog" ref="modal"> 
     <button 
      type="button" 
      className="mdl-button mdl-js-button mdl-button--icon helper-modal-button--close" 
      onClick={this.close} 
     > 
      <i className="material-icons">clear</i> 
     </button> 
     {this.props.children} 
     </dialog> 
    ); 
    } 
}; 

標題很簡單,但這種抽象的類名,並讓我補充如果我需要它,內部不同的東西。

var ModalTitle = React.createClass({ 
    render: function() { 
    return (
     <h2 className="mdl-dialog__title">{this.props.children}</h2> 
    ); 
    } 
}); 

內容與標題幾乎相同。

var ModalContent = React.createClass({ 
    render: function() { 
    return (
     <div className="mdl-dialog__content"> 
     <form id="modal-form">{this.props.children}</form> 
     </div> 
    ); 
    } 
}); 

現在採取的行動,並在我需要幫助:

var ModalActions = React.createClass({ 
    render: function() { 
    return (
     <div className="mdl-dialog__actions"> 
     <button type="button" className="mdl-button" onClick={this.save}>Save</button> 
     {this.props.children} 
     </div> 
    ); 
    } 
}); 

現在,你看,我已經包括了拯救行動的行動,因爲我想擁有它的每模式,但問題是我怎樣才能訪問的保存功能?我認爲我不能把它作爲父母的道具來傳遞,我想我們不得不攔截它的孩子,檢查它併爲它的保存功能提供支持,但是我找不到任何好的信息。如何正確地做到這一點,而不是如何確定哪一個孩子是行動者之一。

我相信最有效的另一種方式是如果我可以將保存功能暴露給所有的孩子,並且只對保存操作採取行動。這也可以讓我編寫利用's'API'的自定義操作。

儘管如此,我還沒有找到任何關於如何做到這一點的好信息,任何想法?

+0

只是通過-function保存爲支柱,並呼籲像'this.props與新道具的每個元素(淺合併)。 onSave' – Hardy

+0

從哪裏?請記住保存功能是的一部分,並且我從另一個組件中寫入,而不是的內部,所以我無法訪問它,並且整個想法是我不想傳遞道具給「內置」的功能來保持抽象。 – MarcusWasTaken

回答

1

您可以使用React.Children遍歷孩子,然後克隆使用React.cloneElement

render: function() { 
    const childrenWithProps = React.Children.map(this.props.children, 
    (child) => React.cloneElement(child, { 
     doSomething: this.doSomething 
    }) 
    ); 

    return <div>{childrenWithProps}</div> 
    }