如何在React

时间:2015-11-25 22:39:30

标签: javascript css d3.js reactjs

所有

我是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()));
          });
    });

此代码片段包含动态添加元素,staic样式,动态样式,动画,在数据可视化中非常常见,但我有点如何在React中实现这个简单模式。

感谢任何例子。

1 个答案:

答案 0 :(得分:0)

示例代码:



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'));
&#13;
<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>
&#13;
&#13;
&#13;