【问题标题】:How to implement D3.selectAll.data.enter.append.transition.style in React如何在 React 中实现 D3.selectAll.data.enter.append.transition.style
【发布时间】:2015-11-25 22:39:30
【问题描述】:

全部:

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

这段代码sn-p涉及动态添加元素,静态样式,动态样式,动画,在数据可视化中很常见,但我有点困惑如何在React中实现这个简单的模式。 p>

感谢您提供任何示例。

【问题讨论】:

    标签: javascript css d3.js reactjs


    【解决方案1】:

    示例代码:

    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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-03
      • 2016-09-30
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-12
      相关资源
      最近更新 更多