为什么D3 Brush在React App中不清除多图
Why does D3 Brush Not Clear Multiple Graphs in React App
我在同一个 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);
}
我在同一个 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);
}