D3JS 换行文本插件在更新数据后被覆盖

D3JS wrap text plugin overwritten after updating the data

我一直在使用此处接受的答案中的解决方案 在树形图上环绕文本Wrapping Text in D3

然而,当我更新数据时,如:

nodeUpdate
  .selectAll("text.nodeText")
  .text(function(d) {
    return d.name;
  })
  .call(wrap, 100)
  .style("fill-opacity", 1);

环绕效果消失

我做错了什么?

____Edit 显示更多 code____

每个节点都添加了通常的 D3JS 过程(进入、更新、退出)。问题是换行更新的文本不起作用。

所以我们进入节点

var nodeEnter = node
  .enter()
  .append("g")
  .call(dragListener)
  .attr("class", "node")
  .attr("transform", function(d) {
    return "translate(" + source.y0 + "," + source.x0 + ")";
  })
  .on("click", click);

我们追加元素到节点,如感兴趣的文本:

nodeEnter 
  .append("text")
  .attr("x", 5)
  .attr("dy", ".95em")
  .attr("class", "nodeText")
  .attr("text-anchor", "start")
  .text(function(d) {
    return d.name;
  })
  .call(wrap, 150);
如果我们不更新这些节点,

包装工作正常。但是在如下更新后:

var nodeUpdate = node
  .transition()
  .duration(duration)
  .attr("transform", function(d) {
    return "translate(" + d.y + "," + d.x + ")";
  });

nodeUpdate
  .selectAll("text.nodeText")
  .text(function(d) {
    return d.name;
  })
  .style("fill-opacity", 1)
  .call(wrap, 130);

文本不再适合换​​行。 wrap函数来自上面引用的Whosebug,查看link.

我刚刚在别处遇到了同样的问题。这是因为文本换行功能不能作用于过渡,它需要选择。要修复您的代码,只需将文本添加和 wrap 调用移动到转换之前:

node
  .selectAll("text.nodeText")
  .text(function(d) {
    return d.name;
  })
  .call(wrap, 130);

var nodeUpdate = node
  .transition()
  .duration(duration)
  .attr("transform", function(d) {
    return "translate(" + d.y + "," + d.x + ")";
  });

nodeUpdate
  .selectAll("text.nodeText")
  .style("fill-opacity", 1)