2015-11-06 231 views
3

當我添加一個帶有反應的標籤時,其父元素已經升級。所以調用upgradElement不起作用,添加的選項卡不起作用。 什麼解決方案,使用容器重新創建所有選項卡並升級它?在這種情況下,React只更新DOM組件,我需要卸載組件?動態添加標籤upgradeElement

回答

4

如何中的特定成分

componentDidUpdate() { 
     componentHandler.upgradeElement(this.refs.myElement); 
     //or componentHandler.upgradeDom('MaterialTabs'); 
    } 

EDIT 1凸片部件

componentDidUpdate() { 

     componentHandler.upgradeDom(); 
    } 

    newTab() { 
     this.setState({ 
      newtab: 1 
     }); 
    } 

    render() { 

     return (<div className="mdl-layout mdl-js-layout mdl-layout--fixed-header" key={this.state.newtab}> 
      <button onClick={this.newTab.bind(this)}>Add Tab</button> 
       <header className="mdl-layout__header"> 
        <div className="mdl-layout__tab-bar mdl-js-ripple-effect"> 
         <Link to="/tabtest" hash="#scroll-tab-1" className="mdl-layout__tab is-active">Tab 1</Link> 
         <Link to="/tabtest" hash="#scroll-tab-2" className="mdl-layout__tab">Tab 2</Link> 
         { this.state.newtab ? 
         <Link to="/tabtest" hash="#scroll-tab-3" className="mdl-layout__tab">Tab 3</Link> : null} 
        </div> 
       </header> 
      <div className="mdl-layout__content"> 
       <section className="mdl-layout__tab-panel is-active" id="scroll-tab-1"> 
        <div className="page-content">Tab 1</div> 
       </section> 
       <section className="mdl-layout__tab-panel" id="scroll-tab-2"> 
        <div className="page-content">Tab 2</div> 
       </section> 
       { this.state.newtab ? <section className="mdl-layout__tab-panel" id="scroll-tab-3"> 
        <div className="page-content">Tab 2</div> 
       </section> : null} 
      </div> 
     </div>); 

    } 
的componentDidUpdate相位主叫componentHandler.upgradeElement()或componentHandler.upgradeDom()

我做了一些測試,可以重現問題。什麼幫助將關鍵屬性放在選項卡組件的根元素上。當添加一個新標籤時,這個鍵必須改變,反應會丟棄組件並完全重新渲染。通過這種方式,所有material-design-lite屬性都會丟失,並且在調用upgradeDom或upgradeElement之後它就可以工作。

React and Material-Design-Lite

Material-Design-Lite source

+0

這就是我所做的,調用componentHandler.upgradeDom(),但它什麼都不做,因爲我認爲TabContainer已經升級,所以它不會深入DOM。我會嘗試升級元素的特定標籤... –

+1

事實上,標籤元素不是可降解元素,這是可降解且已升級的div容器。所以我不知道如何強制upgradeElement。 –

+0

好的,你必須在tabcontainer上使用forceUpdate,當你添加一個選項卡然後調用this.upgradeElement。我也會嘗試自己。 –

0

https://facebook.github.io/react/docs/component-api.html

forceUpdate

無效forceUpdate( [回調函數] )

默認情況下,當你的組件的狀態或道具的變化,您的組件將重新呈現。但是,如果這些變化隱式地改變(例如:對象內部的數據改變而不改變對象本身),或者如果render()方法依賴於其他數據,則可以通過調用來告訴React它需要重新運行render強制性升級()。

調用forceUpdate()將導致在組件上調用render(),跳過shouldComponentUpdate()。這將觸發子組件的正常生命週期方法,包括每個子組件的shouldComponentUpdate()方法。如果標記更改,React仍然只會更新DOM。

通常情況下,您應該儘量避免使用forceUpdate(),只能從render.props和this.state中讀取render()。這使得你的組件「純粹」,你的應用程序變得更簡單,更高效。

+0

我同意但反應更新dom,但MDL已升級它,所以新的選項卡呈現,但MDL選項卡容器已標誌已升級,因此新選項卡不工作。我需要將所有組件dom重新創建爲其初始狀態(在MDL升級之前)。 –

+0

我想我需要在componentWillUnmount函數中降級DOM。 MDL有這個功能嗎? –

+0

我不使用MDL,所以不知道。 –

0

爲了突出基督教斯氏的回答的最重要的部分:

給周邊.mdl-js-tabs div元素的標籤數爲key屬性。

無論何時添加選項卡,該鍵都會改變,React將重新渲染整個選項卡組件。這將隨後進行MDL升級。