为ReactJS包装旧版小部件

时间:2014-08-19 07:24:37

标签: javascript reactjs

我有一个函数gauge(dom_element, value, max),它在一个元素(使用画布)中绘制一个标尺(带针)。

窗口小部件没有更新方法,您必须再次调用它以删除旧窗口小部件并使用新值绘制新窗口小部件。

如何更换ReactJS状态value时,如何调整此函数以重新创建量表?

1 个答案:

答案 0 :(得分:3)

您可以将此模式用于您正在包装的任何插件;当有事件时,有些人需要更多等等。

var Gauge = React.createClass({

  // handle the first mount and updates
  // in this case there's no difference between init and update
  // with the gauge widget, so these just delegate to updateGauge
  componentDidMount: function(){ 
    this.updateGauge(this.props.value, this.props.max); 
  },
  componentWillReceiveProps: function(nextProps){ 
    if (nextProps.value !== this.props.value) {
      this.updateGauge(nextProps.value, nextProps.max);
    }
  },

  // render an empty div, which will be `this.getDOMNode()` in the following function
  render: function(){ return <div />; },

  // actually tell the plugin to run
  updateGauge: function(value, max){
    gauge(this.getDOMNode(), value, max);
  },

  // clean up after the gauge widget
  // sometimes you don't need anything here, but if you do
  // you'll get a nice error from react when it's unmounted :-)
  componentWillUnmount: function(){
    // ...
  }
});