如何将现有文本元素转为d3plus-text文本框?报错排查咨询
That error usually crops up when the d3plus-text TextBox component can’t access the data it needs to render properly. The reduce method is being called on an undefined value, which means the component isn’t receiving the expected data context from your selected elements.
Let’s break down what’s going wrong in your code:
- You’re manually creating
<text>elements first, then trying to pass them toTextBox. But d3plus-text’s components are built to be data-driven—they expect to work with bound data, not just raw DOM elements. Your existing<text>elements likely don’t have the data context the component needs to handle resizing and layout logic.
Here are two reliable fixes:
Solution 1: Let TextBox handle text creation (recommended)
Instead of pre-making the <text> elements, let the TextBox component generate them directly from your node data. This aligns with d3plus’s core data-driven design:
// Assuming `node` is your existing selection of SVG nodes new d3PlusText.TextBox() .data(node.data()) // Pass the data bound to your nodes .select(node) // Select the node containers to append text to .text((d: any) => d.properties.name) // Define text content from your data .class("nodeText") .fontResize(true) .width(options.nodeRadius) .render();
Solution 2: Ensure existing text elements have bound data
If you need to keep your manually created <text> elements, explicitly bind the original node data to each one so TextBox can read it:
// Bind the node's data to each text element explicitly node.append("text") .datum((d: any) => d) // Attach the original node data to the text element .text((d: any) => d.properties.name) .attr("class", "nodeText"); // Now call TextBox with the data-bound elements new d3PlusText.TextBox() .select(".nodeText") .fontResize(true) .width(options.nodeRadius) .render();
Quick Bonus Check
Double-check your d3plus-text version—some older releases had edge-case bugs when handling DOM elements without bound data. Upgrading to the latest stable version might resolve the issue if it’s a known bug.
内容的提问来源于stack exchange,提问作者Uros Velickovic

