不能对 D3 v4 中的对象使用 attr [英] Cannot use attr with an object in D3 v4

查看:19
本文介绍了不能对 D3 v4 中的对象使用 attr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试转换一个不错的 D3 图表示例(https://jsfiddle.net/thudfactor/HdwTH/ ) 到具有新 D3 v4 的 Angular2 组件.

I've been trying to convert a nice D3 chart example ( https://jsfiddle.net/thudfactor/HdwTH/ ) to an Angular2 component with the new D3 v4.

但是我确实得到了无法读取 null 的属性文本";以下代码例外:

I do however get a "cannot read property text of null" exception with the following code:

var textLabels = labelGroups.append("text").attr({
    x: function (d, i) {
        var centroid = pied_arc.centroid(d);
        var midAngle = Math.atan2(centroid[1], centroid[0]);
        var x = Math.cos(midAngle) * cDim.labelRadius;
        var sign = (x > 0) ? 1 : -1
        var labelX = x + (5 * sign)
        return labelX;
    },
    y: function (d, i) {
        var centroid = pied_arc.centroid(d);
        var midAngle = Math.atan2(centroid[1], centroid[0]);
        var y = Math.sin(midAngle) * cDim.labelRadius;
        return y;
    },
    'text-anchor': function (d, i) {
        var centroid = pied_arc.centroid(d);
        var midAngle = Math.atan2(centroid[1], centroid[0]);
        var x = Math.cos(midAngle) * cDim.labelRadius;
        return (x > 0) ? "start" : "end";
    },
    'class': 'label-text'
}).text(function (d, i) {      <--------------- exception
    return d.data.label;
});

labelgroups 是一个选择,append 应该可以工作,所以它一定是导致问题的 .attr({}).然而,它在 jsfiddle 中运行良好.

labelgroups is a selection, append should work, so it must be the .attr({}) causing the problem. It does however work fine in the jsfiddle.

此语法在 D3 v4 中有更改吗?怎么会是正确的?

Has this syntax changed in D3 v4? How would it be correct?

推荐答案

从 D3 v4 开始,您不能使用对象来设置 attrstyle 没有了.为此,您必须引用迷你库 D3-selection-multi:

From D3 v4 onwards you cannot use objects to set attr or style anymore. To do so, you have to reference the mini library D3-selection-multi:

<script src="https://d3js.org/d3-selection-multi.v0.4.min.js"></script>

这样做之后,将您的代码从 attr 更改为 attrs(是的,就像复数一样):

After doing that, change your code from attr to attrs (yes, like a plural):

var textLabels = labelGroups.append("text").attrs({
    //mind the 's' here-------------------------ˆ
});

对样式做同样的处理:它应该是 styles,作为复数,而不是 style.

Do the same for the styles: it should be styles, as a plural, not style.

如果您不想改变这一切,只需按照常规"进行即可方式:在单独的attr中设置xytext-anchorclass.

If you don't want to change all this, simply do as the "regular" way: set x, y, text-anchor and class in separate attr.

这是 selection-multi 文档:https://github.com/d3/d3-selection-multi/blob/master/README.md#selection_attrs

这篇关于不能对 D3 v4 中的对象使用 attr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆