d3.event=null

d3功能奇多, 已经模块化,(其实感觉和react差不多了).

所以默认打包的单个文件

<script src="https://d3js.org/d3.v5.min.js"></script>

或者直接

const d3 = require("d3")

这样默认打包体积大,但是也没有包括全部d3的模块

所以, github官方https://github.com/d3/d3

推荐这样

var d3 = Object.assign({}, require("d3-format"), require("d3-geo"), require("d3-geo-projection"));

尤其是,d3-selection-multi 这个没有默认打包的库,只能这么用. 这样可以使用attrs({}) 直接导入多个属性,尤其适合不需要数据绑定回调函数  (d, i) =>{} 的时候.

但是模块化使用d3的时候, 在响应事件的时候出现了问题.

d3里为了数据绑定需要, 响应事件统一这样:

selection.on('click', (d, i)={
})

而不能用字面的方式得到完整的event信息

selection.attr('onclick', 'callback($event)')

但万能的d3当然也能得到标准dom事件:

selection.on('click', (d, i)={
   const event = d3.event;
   ......
})

但是之但是,在模块导入的时候, 这个d3.event 竟然返回null

稍微搜索了一下,不是1个人遇到这个问题, 参考这个人的发现之后

我这样干:

1导入d3

export const d3Selection = require("d3-selection")
export const d3 = Object.assign({}, event, require("d3-dispatch"), require("d3-selection"), require("d3-selection-multi"), require("d3-geo"));

其他d3功能,照样用下面模块化导入的d3,

而专门导入一个d3Selection 用来处理event

2事件

selection.on('click', (d, i)={
   const event = d3Selection.event;
   ......
})

这样就能得到标准event的各种信息了

比如

event.target.className, event.target.checked

猜你喜欢

转载自www.cnblogs.com/xuanmanstein/p/10631029.html
今日推荐