javascript - 在 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);
解决方案
这两种方法都有效,但第一种更容易出错,因为 D3 可能会意外地与不相关的组件交互,例如当其他组件选择了具有相同类的元素时。
useRef 方法保证了正确的选择,因此在可能的情况下应该首选它。
推荐阅读
- matlab - 关于 matlab 命令“fir1”的混淆
- ansible - Ansible 成为用户不运行 /etc/profile
- r - 根据该行的另一列中的值对列中的值进行操作的更好方法?
- css - 如何在我的渐变中添加渐变不透明度?
- php - 在页面导航上清除了 Angular php-jwt 令牌
- python - Scrapy Splash formrequest.formresponse, - 停留在识别动态加载页面的表单数据
- c - 什么是 C 等价于 Matlab 的索引表达式 A(:,n)?
- angular - 日历显示“NaN”而不是“June”
- python-3.x - 将日期名称转换为数值
- java - 注释处理器和匿名类