如何在React中实现D3.selectAll.data.enter.append.transition.style



全部:

我是React的新手,我想做的是一个基于D3.js的数据可视化应用程序,D3中的一个常见情况是:

var color = d3.scale.category20();
d3.select("body" /*here is any parent root container, not just body*/)
    .data([1,2,3,4])
    .enter()
    .append("div")
    .style("background-color", function(d, i){
        return color(i); // just diff colors
    })
    .style("width", "0px")
    .style("height", "50px")
    .transition()
    .duration(800)
    .style("width", function(d, i){
        return (10+i*10)+"px";
    })
    .on("click", function(d,i){
        d3.select(this)
          .style("background-color", function(){
              return color(Math.floor(10*Math.random()));
          });
    });

这个代码片段调用了动态添加元素、静态风格、动态风格、动画,在数据可视化中很常见,但我有点困惑如何在React中实现这个简单的模式

谢谢你的任何例子。

示例代码:

class App extends React.Component {
  constructor() {
    super();
  }
  componentDidMount() {
    const color = d3.scale.category20();
    d3.select(this.refs.chart /*here is any parent root container*/ )
      .data([1, 2, 3, 4])
      .enter()
      .append("div")
      .style("background-color", function(d, i) {
        return color(i); // just diff colors
      })
      .style("width", "0px")
      .style("height", "50px")
      .transition()
      .duration(800)
      .style("width", function(d, i) {
        return (10 + i * 10) + "px";
      })
      .on("click", function(d, i) {
        d3.select(this)
          .style("background-color", function() {
            return color(Math.floor(10 * Math.random()));
          });
      });
  }
  render() {
    return ( <div>
      <div id="chart" ref="chart"></div>
      </div>
    )
  }
}
ReactDOM.render( <App /> , document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

最新更新