2017-10-04 82 views
-1

我正在創建一個React應用程序,需要添加一些自定義的D3圖表。我想將圖表合併到應用程序'流程'中,並使用React組件生命週期方法,但我也希望能夠像我習慣的那樣以自己的方式編寫D3代碼(輸入 - 更新 - 退出模式等),而不包裹React組件中的單個部分,如vxreact-d3正在執行。我怎樣才能最好地結合React和D3,但仍然像我一直使用D3一樣?

到目前爲止,我發現 - react-faux-dom這似乎很有前途,但該項目需要包含儘可能少的外部依賴性。

+0

第一個Google搜索結果:[與React和D3交互的應用程序](https:// medium .com/@ Elijah_Meeks/interactive-applications-with-react-d3-f76f7b3ebc71) –

+0

沒有看到你做了什麼,我們無法就任何事情提供建議。詢問例子是關鍵問題,所以我們不能這樣做。您的問題對於SO平臺來說過於寬泛,在這個平臺上,您可以提出具體的問題,並提供具體的答案:https://stackoverflow.com/help/how-to-ask – Rob

+0

@ChaseDeAnda您的權利。其實其中一個帖子是我根據自己的回答。只是想我會在這裏分享我自己的解決方案。 –

回答

0

經過我自己的進一步研究後,我發現這可以通過爲圖表創建一個React Higher-Order Component (HOC)來實現。

HOC將像基本/包裝組件一樣工作,通過圖表數據並在必要時增強任何屬性。使用陣營的生命週期方法,它調用類似的方法(創建,更新,銷燬)的圖表實例,可以僅僅把像ES6類或者一個功能,只要它實現了正確的方法

function withChart(ChartComponent) { 
    class ChartHOC extends React.Component { 

     constructor(props) { 
      super(props); 

      this.chart = new ChartComponent(); 
     } 

     componentDidMount() {    
      this.chart.create(this.container); 
     } 

     componentDidUpdate() {    
      this.chart.update(); 
     } 

     render() { 
      return (
      <div className='chartContainer'ref={(el) => { this.container = el; }}></div>); 
     } 
    } 

    return ChartHOC; 
} 

class BarChart { 
    // Mandatory function when using chartHOC 
    create(containerEl) { 
     ... 
    } 

    // Mandatory function when using chartHOC 
    update(props) { 
    ... 
    } 
} 

// wrap the barChart with the chartHOC 
const Example = withChart(BarChart); 

我製作了一個精簡版的chartHOC和一個非常簡單的BarChart示例,它使用HOC:https://jsfiddle.net/marcelk/vf51tvzf/

所以這種方法實現了我想要的。我可以使用React的生命週期方法,傳遞道具React方法,並且仍然編寫D3代碼來管理圖表的行爲,轉換等。