gpt4 book ai didi

javascript - 使用可变尺度时区分 React 和 D3 的关注点

转载 作者:行者123 更新时间:2023-12-01 02:06:45 24 4
gpt4 key购买 nike

我一直在关注Shirley Wu's post about using React with D3并将关注点分成单独的文件。这个想法是 visualization 文件夹中的模块处理 D3 属性。

在我的示例中,文件 visualization/node.js 负责设置表示数据集的圆形节点的属性。它们的位置应基于其值属性和变量比例,该变量比例的域设置为数据值的范围。

比例尺本身是在加载数据的父组件中创建的,因此我看不到任何将其“传递”到节点属性(包括其位置)的 nodeViz.create 的方法) 已设定。我也不相信该函数/模块对数据集有任何了解,无法在 node.js 文件中重新创建比例。

当使用诸如比例之类的东西来定位元素时,有没有办法实现这种分离?感觉好像我错过了什么......

您可以see a version of this in codesandbox.io ,但代码也如下:

Chart.js

import React from "react";

import { extent, scaleLinear, select } from "d3";
import nodeViz from "./visualisation/node";

const width = 800;
const height = 500;

class Chart extends React.Component {
data = [
{ id: 0, value: 4 },
{ id: 1, value: 0 },
{ id: 2, value: 7 },
{ id: 3, value: 5 },
{ id: 4, value: 2 }
];

xScale = scaleLinear()
.range([0, width])
.domain(extent(this.data.map(d => d.value)));

createChart = () => {
// The following would normally happen on componentDidUpdate
// when we have some new data via the props, but in this
// case we're not async so the data will already exist.
const svg = select(this.node);

const nodes = svg.selectAll("circle").data(this.data, d => d.id);

nodes.enter().call(nodeViz.create);
nodes.exit().remove();
};

componentDidMount() {
this.createChart();
}

render() {
return (
<svg ref={node => (this.node = node)} width={width} height={height}>
<g />
</svg>
);
}
}

export default Chart;

可视化/node.js

const create = selection => {
return selection
.append("circle")
.attr("r", 3)
.merge(selection)
.attr("fill", "red")
.attr("cx", d => d.value) // Should be xScale(d.value)
.attr("cy", 150);
};

export default {
create
};

最佳答案

说实话,距离我写那篇文章已经很多年了,我实际上有了一些新的观点(尽管核心概念保持不变)。在这种情况下,属性设置被分离出来,以便能够使用 d3 执行诸如过渡/动画之类的操作(bc d3 需要直接操作 DOM,因此我们不希望 React 跟踪它)。在我看来,比例尺是数据计算和渲染的分离,在这种情况下,我在渲染阶段之前就进行数据计算。所以在那个例子中,数据计算happens in _onChange和渲染happens in renderGraphVisualization.update .

如果我现在就这样做,我可能只会让 React 渲染所有内容(包括属性)或让 D3 渲染所有内容(因此输入-更新-退出所有内容)。我在 this talk 中谈到过这一点.

关于javascript - 使用可变尺度时区分 React 和 D3 的关注点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50047607/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com