如何解决D3.JS | ReactJS筛选器选择“此”冲突问题
原始JavaScript中有一个非常简单的草图
var actives = { active1: false,active2: true,active3: true,active4: false };
var svg = d3.select('body').append('svg').attr('width',512).attr('height',512);
var rect1 = svg.append("rect").attr("class","boxElement active1 active2 active3").attr("x",32).attr("y",32).attr("width",100).attr("height",100).attr("fill","#888888");
var rect2 = svg.append("rect").attr("class","boxElement active1 active4").attr("x",160).attr("y","#DDDDDD");
d3.selectAll('.boxElement').filter(function(){ var classes = d3.select(this).attr("class"); console.log(classes); var sum = false; Object.keys(actives).forEach(function(a_){ if(classes.includes(a_)){ console.log("found"); sum += actives[a_]; }}); return sum > 0 ? true : false }).attr("fill","#00FF00");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
在这种情况下,console.log(d3.select(this))返回矩形类,这是正确的。我需要在过滤器内编写一些函数(而不是d3.select(this).attr("class").includes("whatever")
),以根据类的变化来选择哪些rects是青色的。
但是,我需要在ReactJS中做同样的事情,看来'this'是保留的,并过滤console.log(d3.select(this))返回组件本身。
语法.filter(function(item_){ console.log(item_); return true; })
不能正常工作,它返回undefined
,而console.log(item_.attr("class"))
返回错误。
因此,如果d3.select(this)
不起作用,如何在过滤器方法中一个接一个地访问每个选择及其属性?
解决方法
这不是一个很好的解决方案,但是它可以工作。我正在使用.nodes().map(...)
import React,{ useEffect,useRef } from "react";
import ReactDOM from "react-dom";
import * as d3 from "d3";
import "./styles.css";
function App() {
return (
<div className="App">
<MockupD3 id="d3svg" />
</div>
);
}
class MockupD3 extends React.Component {
constructor(props_) {
super(props_);
this.actives = { active1: false,active2: true,active3: true,active4: false };
this.clickMe = this.clickMe.bind(this);
}
clickMe(){
let this_ = this;
d3.selectAll('.box').nodes().map(node_ => {
let sum = 0;
Object.keys(this_.actives).forEach(key_ =>{
let classes = node_.attributes.class.value;
if(classes.includes(key_)){
sum += this_.actives[key_];
}
})
if(sum > 0) { node_.attributes.fill.value = "#00FF00"; }
else { node_.attributes.fill.value = "#FF0000"; }
})
}
render() {
return ( <svg id="mockup" width={512} height={512}>
<rect class={'box active1 active2 active3'} x={64} y={64} width={64} height={64} fill={'#888888'}></rect>
<rect class={'box active1 active4'} x={160} y={64} width={64} height={64} fill={'#222222'}></rect>
<rect class={''} x={64} y={140} width={160} height={32} fill={'#0000FF'} onClick={this.clickMe}></rect>
</svg> )
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />,rootElement);
https://codesandbox.io/s/d3-react-hooks-forked-2lihv?file=/src/index.js:0-1411
仍在寻找filter()方法。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。