返回每个D3基准的React组件

时间:2018-10-24 09:08:57

标签: reactjs d3.js

我有这个简单的React组件

import React from "react";
import * as D3 from "d3";

class App extends React.Component {
  app = null;

  componentDidMount() {
    let ref = null;
    const p = <p ref={node => ref = node} />
    const ps = D3.select(this.app)
      .selectAll(ref)
      .data([1, 2, 3, 1, 2, 3, 1, 2, 3]);
    ps.enter()
      .append('p')
      .text(d => "hello" + d);
  }
  render() {
    return (
      <div className="App" ref={node => this.app = node}>
        <p>Hello world</p>
        <p>Hello world</p>
      </div>
    );
  }
}

我正在尝试达到.append(<MyComponent />)之类的目的,以便动态添加反应组件。

假设我有一些组件<Card />,例如,对于.select(...).data(...)中的每个数据,我想附加此Card组件并将其添加到DOM。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

一种解决方案是这样做

class App extends React.Component {
...
getCardComponent = (d3Node) => {
  return d3Node
    .append('div')
    .attr('class', 'hex')
    .attr('d', hexPath)
    .attr('fill', hexFill)
    .attr('stroke', 'transparent')
    .attr('stroke-width', 4)
    // ...etc

追加后的所有属性都代表组件的属性...还有更好的主意吗?