将反应app.js中的数据导入反应chart.js

时间:2018-03-01 15:31:46

标签: javascript reactjs d3.js

我创建了React应用程序。

index.js ,它从result_data.json导入数据。

import React from 'react';
import { render } from 'react-dom';
import anime from 'animejs';

import ReactApp from './App';
import Chart from './chart';
import obj from './result_data.json'

let getProperty = function (propertyName) {
    return obj[propertyName];
};

const data = obj;

const App = () => (
    <ReactApp data={data} data2={obj} chart={(<Chart/>)}/>
);

render(<App />,document.getElementById('root'));    

chart.js 我将此图表连接到我的主项目(App.js)。 但我无法从app.js获取chart.js的数据

import { scaleOrdinal } from 'd3-scale';
import { arc, pie } from 'd3-shape';
import { shuffle } from 'd3-array';
import { easeExpOut } from 'd3-ease';
import sortBy from 'lodash/sortBy';
import Surface from 'docs/src/components/Surface';
import React, { PureComponent } from 'react';
import NodeGroup from 'react-move/NodeGroup';

const colors = scaleOrdinal()
  .range(['#a6cee3', '#1f78b4', '#b2df8a', '#33a02c']);

const view = [1000, 550]; // [width, height]
const trbl = [10, 10, 10, 10]; // [top, right, bottom, left] margins

const dims = [ // Adjusted dimensions [width, height]
  view[0] - trbl[1] - trbl[3],
  view[1] - trbl[0] - trbl[2],
];

const mockData = [
  {
    name: 'Linktype',
  }, {
    name: 'Quaxo',
  }, {
    name: 'Skynoodle',
  }, {
    name: 'Realmix',
  }, {
    name: 'Jetpulse',
  }
];

const radius = (dims[1] / 2) * 0.70;

const pieLayout = pie()
  .value((d) => d.value)
  .sort(null);

const innerArcPath = arc()
  .innerRadius(radius * 0.4)
  .outerRadius(radius * 1.0);

const outerArcPath = arc()
  .innerRadius(radius * 1.2)
  .outerRadius(radius * 1.2);

function mid(d) {
  return Math.PI > (d.startAngle + (d.endAngle - d.startAngle));
}

function getRandom(min, max) {
  return Math.floor(Math.random() * (max - (min + 1))) + min;
}

function getArcs() {
  const data = shuffle(mockData)
    .map(({ name }) => ({ name, value: getRandom(10, 100) }));

  return pieLayout(sortBy(data, (d) => d.name));
}

class Example extends PureComponent {
  state = {
    arcs: getArcs(),
  }

  update = (e) => {
    e.preventDefault();
    e.stopPropagation();

    this.setState(() => ({
      arcs: getArcs(),
    }));
  }

  render() {
    const { arcs } = this.state;

    return (
      <div>
        <button onClick={this.update}>
          Update
        </button>
        <Surface view={view} trbl={trbl}>
          <g transform={`translate(${dims[0] / 2}, ${dims[1] / 2})`}>
            <NodeGroup
              data={arcs}
              keyAccessor={(d) => d.data.name}

              start={({ startAngle }) => ({
                startAngle,
                endAngle: startAngle,
              })}

              enter={({ endAngle }) => ({
                endAngle: [endAngle],
                timing: { duration: 500, delay: 350, ease: easeExpOut },
              })}

              update={({ startAngle, endAngle }) => ({
                startAngle: [startAngle],
                endAngle: [endAngle],
                timing: { duration: 350, ease: easeExpOut },
              })}
            >
              {(nodes) => {
                return (
                  <g>
                    {nodes.map(({ key, data, state }) => {
                      const p1 = outerArcPath.centroid(state);
                      const p2 = [
                        mid(state) ? p1[0] + (radius * 0.5) : p1[0] - (radius * 0.5),
                        p1[1],
                      ];
                      return (
                        <g key={key}>
                          <path
                            d={innerArcPath(state)}
                            fill={colors(data.data.name)}
                            opacity={0.9}
                          />
                          <text
                            dy="4px"
                            fontSize="12px"
                            transform={`translate(${p2.toString()})`}
                            textAnchor={mid(state) ? 'start' : 'end'}
                          >{data.data.name}</text>
                          <polyline
                            fill="none"
                            stroke="rgba(127,127,127,0.5)"
                            points={`${innerArcPath.centroid(state)},${p1},${p2.toString()}`}
                          />
                        </g>
                      );
                    })}
                  </g>
                );
              }}
            </NodeGroup>
          </g>
        </Surface>
      </div>
    );
  }
}

export default Example;

App.js 。这是我的主要项目。它从index.js

获取数据
import React from 'react';
import {Group} from '@vx/group';
import {Tree} from '@vx/hierarchy';
import {LinearGradient} from '@vx/gradient';
import {hierarchy} from 'd3-hierarchy';
import {pointRadial} from 'd3-shape';
import NodeGroup from 'react-move/NodeGroup';
import Surface from './components/Surface';

const view = [1200, 750]; // [width, height]
const trbl = [10, 10, 30, 10]; // [top, right, bottom, left] margins

function findCollapsedParent(node) {
    if (!node.data.isExpanded) {
        return node;
    } else if (node.parent) {
        return findCollapsedParent(node.parent);
    } else {
        return null;
    }
}

function radialPoint(angle, radius) {
    const [x, y] = pointRadial(angle, radius);
    return {x, y};
}

export default class extends React.Component {

    render() {
        const {
            width = view[0],
            height = view[1] - 30,
            data,
            chart,
            margin = {
                top: 10,
                left: 10,
                right: 10,
                bottom: 30
            }
        } = this.props;

        const innerWidth = width - margin.left - margin.right;
        const innerHeight = height - margin.top - margin.bottom;

        let sizeWidth = 2 * Math.PI;
        let sizeHeight = Math.min(innerWidth, innerHeight) /2;
        let origin;

        origin = {
            x: innerWidth / 2,
            y: innerHeight / 2
        };

        if (width < 10) return null;
        return (
            <div>                    

                <div id={"chart"}>
                    {this.getChart}
                </div>

                <Surface view={view} trbl={trbl}>

                    <LinearGradient id="lg" from="#fd9b93" to="#fe6e9e"/>
                    {/*<rect width={width} height={height} rx={0} fill="#232323"/>*/}

                    <Tree
                        top={margin.top}
                        left={margin.left}
                        root={hierarchy(data, d => (d.isExpanded ? d.children555 || d.children2 : null))}
                        size={[sizeWidth, sizeHeight]} 
                        separation={(a, b) => ((a.children === b.children) && (a.parent === b.parent) ? 1 : 7) / a.depth }
                    >

                        {({links, descendants}) => (
                            <Group top={origin.y} left={origin.x}>
                                <NodeGroup
                                    data={links}
                                    keyAccessor={(d, i) =>
                                        `${d.source.data}_${d.target.data.name}`}

                                    start={({source, target}) => {
                                        return {
                                            source: {
                                                x: source.data.x0,
                                                y: source.data.y0
                                            },
                                            target: {
                                                x: source.data.x0,
                                                y: source.data.y0
                                            }
                                        };
                                    }}

                                    enter={({source, target}) => {
                                        return {
                                            source: {
                                                x: [source.x],
                                                y: [source.y]
                                            },
                                            target: {
                                                x: [target.x],
                                                y: [target.y]
                                            },

                                        };
                                    }}
                                    update={({source, target}) => {
                                        return {
                                            source: {
                                                x: [source.x],
                                                y: [source.y]
                                            },
                                            target: {
                                                x: [target.x],
                                                y: [target.y]
                                            }
                                        };
                                    }}

                                    leave={({source, target}) => {
                                        const collapsedParent = findCollapsedParent(source);
                                        return {
                                            source: {
                                                x: [collapsedParent.data.x0],
                                                y: [collapsedParent.data.y0]
                                            },
                                            target: {
                                                x: [collapsedParent.data.x0],
                                                y: [collapsedParent.data.y0]
                                            }
                                        };
                                    }}
                                >
                                    {nodes => (
                                        <Group>
                                            {nodes.map(({key, data, state}) => {
                                                return (
                                                    <LinkRadialCurve
                                                        data={state}
                                                        stroke="#2996D9"
                                                        strokeWidth="1"
                                                        strokeDasharray="4"
                                                        fill="none"
                                                        key={key}
                                                    />
                                                );
                                            })}
                                        </Group>
                                    )}
                                </NodeGroup>

                                <NodeGroup
                                    data={descendants}
                                    keyAccessor={d => d.data.name}
                                    start={({parent}) => {
                                        const radialParent = radialPoint(parent ? parent.x : 0, parent ? parent.y : 0);
                                        return {
                                            x: radialParent.x,
                                            y: radialParent.y,
                                            opacity: 0
                                        };
                                    }}
                                    enter={({x, y}) => {
                                        const point = radialPoint(x, y);
                                        return {
                                            x: [point.x],
                                            y: [point.y],
                                            opacity: [1],
                                            timing: {duration: 600, delay: 200}
                                        };
                                    }}
                                    update={({x, y}) => {
                                        const point = radialPoint(x, y);
                                        return {
                                            x: [point.x],
                                            y: [point.y],
                                            opacity: [1]
                                        };
                                    }}
                                    leave={({parent}) => {
                                        const collapsedParent = findCollapsedParent(parent);
                                        const radialParent = radialPoint(collapsedParent.data.x0, collapsedParent.data.y0);
                                        return {
                                            x: [radialParent.x],
                                            y: [radialParent.y],
                                            opacity: [0]
                                        };
                                    }}
                                >
                                    {nodes => (
                                        <Group>
                                            {nodes.map(({key, data: node, state}) => {
                                                const width = 50;
                                                const height = 30;
                                                const textLength = node.data.name;

                                                return (
                                                    <Group
                                                        top={state.y}
                                                        left={state.x}
                                                        key={key}
                                                        opacity={state.opacity}
                                                    >
                                                        {node.data.isExpanded && node.depth !== 0 && (
                                                            <circle
                                                                r={'28'}
                                                                fill={'transparent'}
                                                                stroke={'#2996D9'}
                                                                strokeWidth={2.5}
                                                                strokeOpacity={0.9}
                                                            />
                                                        )}

                                                        {node.depth === 0 && (
                                                            <circle
                                                                r={(textLength > 15) ? ('32') : ('39')}
                                                                height={height}
                                                                width={width}
                                                                y={-height / 2} //--FOR RECT ****
                                                                x={-width / 2}
                                                                fill={'#2996D9'}
                                                                stroke='#03c0dc'
                                                                strokeDasharray={"3"}
                                                                strokeWidth={3}

                                                                onClick={() => {
                                                                    console.log('node.onClick', node);
                                                                    if (!node.data.isExpanded) {
                                                                        node.data.x0 = node.x;
                                                                        node.data.y0 = node.y;
                                                                    }
                                                                    node.data.isExpanded = !node.data.isExpanded;
                                                                    this.forceUpdate();
                                                                }}
                                                            />
                                                        )}

                                                        {node.data.children2 && (
                                                            <circle
                                                                r={'22'}
                                                                height={height}
                                                                width={width}
                                                                y={-height / 2} //--FOR RECT
                                                                x={-width / 2}  //--FOR RECT
                                                                fill={
                                                                    node.data.name === 'Skills' ? ('#DA244D') : node.data.name === 'Experience' ?
                                                                        ('#F3B63C') : node.data.name === 'Education' ? ('#64B86C') : ('#F3B63C')
                                                                }
                                                                strokeOpacity={!node.data.children2 ? 0.6 : 1}
                                                                rx={!node.data.children2 ? 10 : 0} //--FOR RECT
                                                                onClick={() => {

                                                                    if (node.data.name === 'Experience') {

                                                                        this.getChart = !chart;
                                                                    }

                                                                    if (!node.data.isExpanded) {
                                                                        node.data.x0 = node.x;
                                                                        node.data.y0 = node.y;
                                                                    }
                                                                    node.data.isExpanded = !node.data.isExpanded;

                                                                    this.forceUpdate();
                                                                    console.log(node);
                                                                }}
                                                            />
                                                        )}

                                                        {!node.data.children2 && !node.data.children555 && (
                                                            <a>
                                                                <rect
                                                                    height={height}
                                                                    width={width}
                                                                    y={-height / 2} //--FOR RECT
                                                                    x={-width / 2}  //--FOR RECT
                                                                    fill={node.data.children ? '#232323' : '#232323'}
                                                                    stroke={'#2996D9'}
                                                                    strokeWidth={2}
                                                                    strokeDasharray={!node.data.children555 ? '2,2' : '0'}
                                                                    // strokeOpacity={!node.data.children ? 0.6 : 1}
                                                                    rx={!node.data.children555 ? 8 : 0}

                                                                    onClick={() => {

                                                                        this.getChart = chart;
                                                                        this.forceUpdate();
                                                                        console.log(node);
                                                                        console.log(this.mockData);
                                                                    }}
                                                                    >

                                                                </rect>
                                                            </a>
                                                        )}

                                                        <title> {node.data.name} </title>

                                                        {node.data.isExpanded || !node.data.children2 || (
                                                            <text
                                                                dy={
                                                                    (textLength.length > 5) ? ('-5') : ('.33em')
                                                                }
                                                                x={
                                                                    (textLength.length < 5) ? ('0') : (textLength.length < 30) ? ('30') : ('-33')
                                                                }

                                                                fontSize={11}
                                                                fontFamily="Arial"
                                                                textAnchor={(textLength.length < 5) ? ('middle') : (textLength.length < 30) ? ('start') : ('end')}
                                                                style={{pointerEvents: 'none'}}
                                                                fill={
                                                                    node.depth === 0 ? ('white') : node.children555 ? ('white') : ('white')
                                                                }
                                                            >
                                                                <tspan> {node.data.name}</tspan>
                                                            </text>

                                                        )}

                                                    </Group>
                                                );
                                            })}
                                        </Group>
                                    )}
                                </NodeGroup>
                            </Group>
                        )}
                    </Tree>
                </Surface>
            </div>
        );
    }
}

chart.js

mockData = [
  {
    name: 'Linktype',
  }, {
    name: 'Quaxo',
  }, {
    name: 'Skynoodle',
  }, {
    name: 'Realmix',
  }, {
    name: 'Jetpulse',
  }
];

但我需要从 App.js

获取数据

如何解决这个问题? 感谢。

1 个答案:

答案 0 :(得分:1)

在App.js中导出mockData = [yourData],在Chart.js中从'./App.js'导出{mockData}检查示例。

App.js

export mockData = [
  {
    name: 'Linktype',
  }, {
    name: 'Quaxo',
  }, {
    name: 'Skynoodle',
  }, {
    name: 'Realmix',
  }, {
    name: 'Jetpulse',
  }
];

在Chart.js

import {mockData} from './App.js'