简体   繁体   中英

When using D3 in React, should I use useRef, or directly select an element by tag/class/Id with D3?

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

For this given div which method is best

a)

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);

Both approaches work, but the first one is more error prone since D3 can accidentally interact with unrelated components, such as when other components have elements with the same class being selected.

The useRef approach guarantees the correct selection, so it should be preferred when possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM