2014-09-22 89 views
1

我是新面板的內容作出反應,並尋找一些最佳實踐。我正在製作一個Chrome擴展程序,它是一個小部件。該小部件有3個部分。請致電Section A,Section BSection C。在小部件頂部我想有按鈕,像這樣:陣營導航控制在低於

[logo]         | Section A | Section B | Section C | 

[ 


     Panel Content (Default Section A) 



] 

並且當單擊這些部分的鏈接之一,下面該節的相關內容更新面板的內容。

我首先想到的是使所有的人,然後就隱藏在面板jQuery show/hide()。它的工作原理,但我寧願不這樣做,因爲每個面板異步加載一些數據,我寧願不預先支付這個價格,如果用戶從不點擊後面的2個鏈接。

我創建反應的組分每個部分所以他們很容易更換。

然後我嘗試這樣做:

showSectionB: function(){ 
    React.renderComponent(
     <SectionBList person={this.props.person} />, 
     document.querySelector('.main .panel') 
    ); 
    }, 

    render: function() { 
    return (
     <div className="main"> 
     <div className="actions"> 
      <button className="T-I-ax7" onClick={this.showSectionB}>Section B</button> 
     </div> 
     <div className="panel"> 
      <SectionAList person={this.props.person} /> 
     </div> 
     </div> 
    ); 
    } 

它認爲更符合邏輯,但感覺怪怪的,我一個組件內深遠的容器放置組件。最重要的是,整個瀏覽器鎖定了,給了我這個消息後面板切換:

React attempted to use reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server. 

有沒有更好的方式來手呢?

回答

2

的關鍵反應是總是通過render()渲染你的應用程序。用戶交互只應觸發重新啓動render()的事件。在你的例子中onClick應該調用setState()來做到這一點。

getInitialState: function() { 
    return { 
     section: "a" 
    }; 
    }, 

    showSectionB: function(){ 
    // Update the component's state for a re-render(). 
    this.setState({ 
     section: "b" 
    }); 
    }, 

    render: function() { 
    if (this.state.section == "a") { 
     var section = <SectionAList person={ this.props.person } />; 
    } 
    else if (this.state.section == "b") { 
     var section = <SectionBList person={ this.props.person } />; 
    } 
    return ( 
     <div className="main"> 
     <div className="actions"> 
      <button className="T-I-ax7" onClick={ this.showSectionB }>Section B</button> 
     </div> 
     <div className="panel"> 
      { section } 
     </div> 
     </div> 
    ); 
    } 

更新感謝您的評論!

+0

存儲狀態的部件就是反應。在文檔大綱[「不應該在狀態去麼?」(https://facebook.github.io/react/docs/interactivity-and-dynamic-uis一個反的.html#什麼,不應該-GO-的狀態)。您可以將其渲染從名爲「isSectionBShown」的布爾值或類似的布爾值中,只存儲'this.state'中的布爾值。 – 2014-09-22 21:36:25

+1

@ssorallen謝謝! – Rygu 2014-09-22 21:56:26

+0

修訂看起來不錯。 – 2014-09-22 22:19:39