使用componentWillReceiveProps上的react props更新d3图表

时间:2017-03-31 14:06:30

标签: reactjs d3.js data-visualization

所以,我有一个d3反应组件,有一些我想改变的事情。但我很难过。特别是通过更新道具来控制d3而无需重绘图形。这是代码:

function createChart(dom, props){
    // var node = d3.select(dom);

    //Remove prev pie chart before drawing new one
    d3.select('#pie').remove();

    var input = d3.selectAll("input")

    var initMeasure = input[0].map(x => {if (x.checked){return(x.value)}})[0]

    var root = props.data

    var width = props.width,
        height = props.height,
        radius = (Math.min(width, height) / 2) - 20;

    var x = d3.scale.linear()
        .range([0, 2 * Math.PI]);

    var y = d3.scale.sqrt()
        .range([0, radius]);

    var color = d3.scale.category20();

    var tooltip = d3.select("body")
        .append("div")
        .attr("id", "tooltip")
        .style("position", "absolute")
        .style("z-index", "10")
        .style("opacity", 0)
        .on("mouseover", mouseOutArc);

    function format_number(x) {
        x = x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        return x
    }


    function format_description(d) {
        var description = d.description;
        return  '<b>' + d.key + '</b></br>'+ '(' + format_number(d.value) + ')';
    }

    function computeTextRotation(d) {
        var angle=(d.x +d.dx/2)*180/Math.PI - 90

        return angle;
    }

    function mouseOverArc(d) {
        d3.select(this).attr("stroke","black")

        tooltip.html(format_description(d));
        return tooltip.transition()
            .duration(50)
            .style("opacity", 0.9);
    }

    function mouseOutArc(){
        d3.select(this).attr("stroke","grey")
        return tooltip.style("opacity", 0);
    }

    function mouseMoveArc (d) {
        return tooltip
            .style("top", (d3.event.pageY-10)+"px")
            .style("left", (d3.event.pageX+10)+"px");
    }

    var root_ = null;

    var svg = d3.select(dom).append("svg")
        .attr("width", width)
        .attr("height", height)
        .attr("id", 'pie')
        .append("g")
        .attr("transform", "translate(" + width / 2 + "," + (height / 2 + 10) + ")");

    var initvalue
    switch(initMeasure) {
        case 'dollars':
            initvalue = function(d) { return d.dollars; };
            break;
        case 'units':
            initvalue = function(d) { return d.units; };
            break;
        case 'tdps':
            initvalue = function(d) { return d.tdps; };
            break;
    }

    var partition = d3.layout.partition()
        .sort(null)
        .value(function(d) { return d.dollars; })
        .children(function(d) {return d.values});

    var arc = d3.svg.arc()
        .startAngle(function(d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x))); })
        .endAngle(function(d) { return Math.max(0, Math.min(2 * Math.PI, x(d.x + d.dx))); })
        .innerRadius(function(d) { return Math.max(0, y(d.y)); })
        .outerRadius(function(d) { return Math.max(0, y(d.y + d.dy)); });

// Keep track of the node that is currently being displayed as the root.
    var node;

    node = root;
    var path = svg.datum(root).selectAll("path")
        .data(partition.nodes)
        .enter().append("path")
        .attr("d", arc)
        .attr("id", "arc")
        .style("fill", function(d) { return color((d.values ? d : d.parent).key); })
        .attr("stroke","grey")
        .transition().duration(750).attrTween("d", arcTweenData)
        .on("click", click)
        .on("mouseover", mouseOverArc)
        .on("mousemove", mouseMoveArc)
        .on("mouseout", mouseOutArc)
        .each(stash);

    d3.selectAll("input").on("change", function change() {
        if (this.name === 'measurement') {
            var value
            switch(this.value) {
                case 'dollars':
                    value = function(d) {return d.dollars};
                    break;
                case 'units':
                    value = function(d) {return d.units};
                    break;
                case 'tdps':
                    value = function(d) {return d.tdps};
                    break;
            }
        }
        path
            .data(partition.value(value).nodes)
            .transition()
            .duration(1000)
            .attrTween("d", arcTweenData);
    });

    function click(d) {
        node = d;
        path.transition()
            .duration(1000)
            .attrTween("d", arcTweenZoom(d));
        console.log('clicked: ', d.key)
    }

    d3.select(self.frameElement).style("height", height + "px");

// Setup for switching data: stash the old values for transition.
    function stash(d) {
        d.x0 = d.x;
        d.dx0 = d.dx;
    }

// When switching data: interpolate the arcs in data space.
    function arcTweenData(a, i) {
        var oi = d3.interpolate({x: a.x0, dx: a.dx0}, a);
        function tween(t) {
            var b = oi(t);
            a.x0 = b.x;
            a.dx0 = b.dx;
            return arc(b);
        }
        if (i == 0) {
            // If we are on the first arc, adjust the x domain to match the root node
            // at the current zoom level. (We only need to do this once.)
            var xd = d3.interpolate(x.domain(), [node.x, node.x + node.dx]);
            return function(t) {
                x.domain(xd(t));
                return tween(t);
            };
        } else {
            return tween;
        }
    }

// When zooming: interpolate the scales.
    function arcTweenZoom(d) {
        var xd = d3.interpolate(x.domain(), [d.x, d.x + d.dx]),
            yd = d3.interpolate(y.domain(), [d.y, 1]),
            yr = d3.interpolate(y.range(), [d.y ? 20 : 0, radius]);
        return function(d, i) {
            return i
                ? function(t) { return arc(d); }
                : function(t) { x.domain(xd(t)); y.domain(yd(t)).range(yr(t)); return arc(d); };
        };
    }

};

@observer
class SunburstChart extends React.Component {

    constructor(props) {
        super(props);
        this.state = {}
    }

    componentDidMount() {
        var dom =  ReactDOM.findDOMNode(this);
        createChart(dom, this.props);
    }

    componentWillReceiveProps(x) {
        console.log('props received: ', x)
        var dom =  ReactDOM.findDOMNode(this);
        createChart(dom, x);

    }


    render() {
        console.log('sunburst chart rendered: ')
        return (
            <div>
                <RadioButtonGroup name="measurement" defaultSelected="dollars">
                    <RadioButton
                        value="dollars"
                        label="Dollars"
                    />
                    <RadioButton
                        value="units"
                        label="Units"
                    />
                    <RadioButton
                        value="tdps"
                        label="Tdps"
                    />
                </RadioButtonGroup>
            </div>
        );
    }
};

当组件收到道具时,我正在重绘图表。但是,我希望能够改变现有的图表。如果这不可能,那么在图表的初始加载上进行一些转换会很棒。

也;查看输入的代码行:

d3.selectAll("input").on("change", function change() {
        if (this.name === 'measurement') {
            var value
            switch(this.value) {
                case 'dollars':
                    value = function(d) {return d.dollars};
                    break;
                case 'units':
                    value = function(d) {return d.units};
                    break;
                case 'tdps':
                    value = function(d) {return d.tdps};
                    break;
            }
        }
        path
            .data(partition.value(value).nodes)
            .transition()
            .duration(1000)
            .attrTween("d", arcTweenData);
    });

如果我能通过道具来控制它,那将是很棒的。

非常感谢任何建议!谢谢你的阅读!

1 个答案:

答案 0 :(得分:-1)

我将回答1.问题。

这是一个想法:

  1. 最初使用代码渲染饼图(以便d3生成带有您提供的ID的svg元素)

  2. 为饼图创建更新函数(参见d3思考连接),当组件接收到新的道具时,执行该函数而不从dom中删除饼图,但只选择你知道的id的现有svg,并指示d3更改svg dom属性for(insert,update-d3 sets)

相关问题