D3 v6如何正确加入?

问题描述

我是D3的新手,我发现的大多数示例都是针对v3的。尝试更新代码以使用联接模式,但无法使其正常运行。它是这样的:

[...]

let link = svg.append("g").attr("class","links").selectAll("path");
let node = svg.append("g").selectAll("g");

function update() {
  node = node
    .data(nodes)
    .join("g",enter => {
      enter
        // Add some stuff...
        .call(drag(simulation)); // This does not work. If I put the call(drag(... after the join it works.
    });
}

[...]

调用方法有什么问题?

解决方法

selection.join()具有三个函数参数:enter,update,exit。您需要将所有代码放入enter函数中,而不使用第一个参数:将字符串用作第一个参数可以使用only if you're only appending that element并且不执行任何其他任务:

node = node
    .data(nodes)
    .join("g") // will only append "g" in the enter selection,can't do anything else

相反,您可以直接在回车选择中追加:

function update() {
  node = node
    .data(nodes)
    .join(enter => {
      enter
        .append("g")
        // Add some stuff...
        .call(drag(simulation)); // This does not work. If I put the call(drag(... after the join it works.
    });
}
,

来自recommended usage of join

回车和更新函数的返回值很重要——它 指定要通过 selection.join 合并和返回的选择。

您没有从 enter 函数返回任何内容。以下应该工作。返回输入选择(注意缺少花括号),因为它被 join 用于 DOM 更新:

[...]

let link = svg.append("g").attr("class","links").selectAll("path");
let node = svg.append("g").selectAll("g");

function update() {
  node = node
    .data(nodes)
    .join("g",enter => 
      enter
        .call(drag(simulation))
    );
}

[...]

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...