问题描述
我是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.
});
}
,
回车和更新函数的返回值很重要——它 指定要通过 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))
);
}
[...]