有两种方法:
一、通过数据data的item去控制
const data = {
nodes: [
{
id: '0',
label: 'B1106\n32874PB',
size: [80, 80],
labelCfg: {
position: 'center',
style: {
fill: '#595959',
fontSize: 14,
},
},
style: {
// fill: 'r(0.5, 0.5, 0.1) 0:#ffffff 1:#1890ff',
fill: 'l(0) 0:#ffffff 0.5:#7ec2f3 1:#1890ff',
stroke: '#5B8FF9',
lineWidth: 1,
},
},
{
id: '1',
label: '1',
},
]
}
之后在const graph = new G6.Graph
配置里添加defaultNode
属性(这么做的目的是设置一个默认节点配置,如果节点没有单独赋值,就会采用以下配置):
defaultNode: {
size: [15, 10],
type: 'circle',
labelCfg: {
position: 'right',
},
style: {
lineWidth: 2,
stroke: '#5B8FF9',
fill: '#C6E5FF',
},
},
二、通过graph.node设置回调函数统一处理
// 以下是重点
graph.node((node) => {
if (node.flag === "b") {
return {
style: {
fill: "#fff",
stroke: "#ea7171",
},
};
}
return {
style: {
fill: "#2db7f5",
stroke: "#ea7171",
},
};
});
完整代码如下:
import { useEffect, useState, memo } from "react";
import G6 from "@antv/g6";
let graph = null;
export default memo(function RelaNew() {
useEffect(() => {
graph && graph.destroy();
const container = document.getElementById("barContainer");
const data = {
nodes: [
{
id: "0",
label: "0",
flag: "b",
},
{
id: "1",
label: "1",
flag: "b",
},
{
id: "2",
label: "2",
flag: "a",
},
{
id: "3",
label: "3",
flag: "b",
},
{
id: "4",
label: "4",
flag: "a",
},
],
edges: [
{
source: "0",
target: "1",
},
{
source: "0",
target: "2",
},
{
source: "0",
target: "3",
},
{
source: "0",
target: "4",
},
],
};
const width = document.getElementById("barContainer").scrollWidth;
const height = document.getElementById("barContainer").scrollHeight || 500;
graph = new G6.Graph({
container: "barContainer",
width,
height,
modes: {
default: ["drag-canvas", "drag-node"],
},
layout: {
type: "fruchterman",
gravity: 5,
speed: 5,
},
animate: true,
defaultNode: {
size: 30,
style: {
lineWidth: 2,
stroke: "#5B8FF9",
fill: "#C6E5FF",
},
},
defaultEdge: {
size: 2,
color: "#e2e2e2",
style: {
endArrow: {
path: "M 0,0 L 8,4 L 8,-4 Z",
fill: "#e2e2e2",
},
},
},
});
// 以下是重点
graph.node((node) => {
if (node.flag === "b") {
return {
style: {
fill: "#fff",
stroke: "#ea7171",
},
};
}
return {
style: {
fill: "#2db7f5",
stroke: "#ea7171",
},
};
});
graph.data(data);
graph.render();
}, []);
return (
<div id="barContainer" style={{ width: "100%", height: "100%" }}></div>
);
});