首页 > 解决方案 > 在 React 中使用 D3 时,我应该使用 useRef,还是直接使用 D3 通过 tag/class/Id 选择元素?

问题描述

<div ref={svgRef} className="App"></div>

对于这个给定的 div 哪种方法最好

一个)

const svg = d3.select('.App')
      .append('svg')
      .attr('width', width + margin.left + margin.right)
      .attr('height', width + margin.top + margin.bottom);

b)

const svgRef = useRef();
const svg = d3.select(svgRef.current)
      .append('svg')
      .attr('width', width + margin.left + margin.right)
      .attr('height', width + margin.top + margin.bottom);

标签: javascriptreactjsd3.jsreact-hooks

解决方案


这两种方法都有效,但第一种更容易出错,因为 D3 可能会意外地与不相关的组件交互,例如当其他组件选择了具有相同类的元素时。

useRef 方法保证了正确的选择,因此在可能的情况下应该首选它。


推荐阅读