2016-08-12 60 views
3

我想使用AnyChart庫與我目前的React,Redux堆棧。有什麼辦法可以包裝AnyCharts,如FauxDom。如果你能給我提供一個示例代碼片段或指向一個庫的方法,那會很好。是否可以將AnyChart的HTML版本與React一起使用?

+0

我不明白爲什麼要將它包裹在FauxDom中?你是否想簡單地將AnyChart引用爲React Component? – whitep4nther

+0

我希望能夠引用AnyChart組件,並且能夠在前端和後端渲染中使用它們。 –

回答

6

至於客戶端的React渲染,肯定可以使用包裝在React組件中的AnyChart。

你可以寫一個包裹AnyChart的部件接受(餅圖包裝的一個例子)在這種方式中的數據陣列和標題作爲道具:

import React, { Component } from 'react'; 

class AnyChart extends Component { 

    constructor(props) { 
    super(props); 
    } 

    // Important, otherwise the re-render 
    // will destroy your chart 
    shouldComponentUpdate() { 
    return false; 
    } 

    componentDidMount() { 

    // Get data from the props 
    let data = this.props.data; 
    let title = this.props.title; 

    // Let's draw the chart 
    anychart.onDocumentReady(function() { 
     let chart = anychart.pie(data); 
     chart.container('chart'); 
     chart.title(title); 
     chart.draw(); 
    }); 
    } 

    render() { 
    return (
     <div id="chart" style={{height: '400px'}}/> 
    ); 
    } 
} 

export default AnyChart; 

然後,可以使用該組件從另一個反應組分。 例如,從功能組件:

import React from 'react'; 
import AnyChart from './AnyChart'; 
const AnyChartTest = (props) => { 

    const data = [ 
    ['React', 5200], 
    ['ES6', 2820], 
    ['Redux', 2650], 
    ['Redux Ducks', 670] 
    ]; 

    return (
    <div> 
     <h1>AnyChart Test</h1> 
     <AnyChart data={data} title="Technology Adoption" /> 
    </div> 
); 
}; 

export default AnyChartTest; 

這種運作良好,如果你不需要有從道具的新數據動態更新圖表。如果是這種情況,您應該在AnyChart包裝器組件中添加一個ComponentWillReceiveProps處理程序,您應該在其中將新數據從道具傳遞到圖表並強制重繪。

斯蒂芬Grider由第三方組件的集成非常好的視頻: https://www.youtube.com/watch?v=GWVjMHDKSfU

我希望我幫助你,至少在客戶端呈現。

Matteo Frana

相關問題