我在同一个React组件的不同元素中有多个图形显示在同一页面上。每个图形使用相同的代码位,但只有第一个图形在选择后清除画笔。所有图形在没有React的常规js
文件中都可以正常工作。
const plotArea = async (props: any) => {
...
// Handler for the end of a brush event from D3.
const brushEnded = (event: any) => {
const s = event.selection;
// Consume the brush action
if (s) {
d3.select('.brush').call(brush.move, null);
}
}
// Create a brush for selecting regions to zoom on.
const brush: any = d3
.brushX()
.extent([
[0, 0],
[width, height - 1],
])
.on('end', brushEnded);
// Zoom brush
svg.append('g').attr('class', 'brush').call(brush);
}
useEffect(() => {
// plotArea() occurs for each graph, there are multiple graphs
plotArea(...);
...
}, []);
当d3在d3.select('.brush').call(brush.move, null);
中运行选择时,它不会将搜索限制到该组件。它将在整个文档中搜索.brush
元素,并在找到第一个元素时停止。
作为快速修复,您可以保存组件的特定笔刷,以便您已经拥有引用并且不需要运行d3.select
来获取它:
const plotArea = async (props: any) => {
...
// Create brushElement first
const brushElement = svg.append('g').attr('class', 'brush');
// Handler for the end of a brush event from D3.
const brushEnded = (event: any) => {
const s = event.selection;
// Consume the brush action
if (s) {
brushElement.call(brush.move, null); // Now uses the variable
}
}
// Create a brush for selecting regions to zoom on.
const brush: any = d3
.brushX()
.extent([
[0, 0],
[width, height - 1],
])
.on('end', brushEnded);
brushElement.call(brush);
}