在js文件中使用jsx代码调用文件中的函数

时间:2017-06-12 18:49:37

标签: reactjs react-jsx

我有三个文件,percentGuageWidget.js,index.html和main.js

percentGuageWidget.js有一些react.js& jsx代码

我得到的renderWidget没有定义。看来如果我在percentGuageWidget.js中调用renderWidget,它运行正常,但在别处调用时它不会工作。

如何制作它以便我可以从该文件外部调用它。



class PercentGuageWidget extends React.Component {  
  constructor(props) {
    super(props);
    this.state = {
      value: 0
    }
   }

  componentDidMount() {
    var widget = this;
    setInterval(function(){
      widget.setState({value:Math.round(Math.random()*100)});
    }, 1000)
  }

  /* The render will be updated whenever state changes are made to the widget */
  render() {
    return (
      <div className="percent-guage-widget widget">
          <div className="bar" style={{width:this.state.value + "%"}}></div>
          <div className="amount">{this.state.value}%</div>  
      </div>
    );
  }
}

var container = document.getElementById('target-widget-container');
function renderWidget(){
  ReactDOM.render(<PercentGuageWidget />, container);
}
&#13;
<html>
    <head>
        <script> var appGlobals = {} </script>
        <script
            src="http://code.jquery.com/jquery-3.2.1.slim.min.js"
            integrity="sha256-k2WSCIexGzOj3Euiig+TlR8gA0EmPjuc79OEeY5L45g="
            crossorigin="anonymous"></script
        <link rel="stylesheet" type="text/css" href="main.css">
    </head>
    <body>
        <div id="target-widget-container"></div>
    </body>

<script src="https://unpkg.com/react@15.0.1/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15.0.1/dist/react-dom.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
    <script type="text/babel" src="widgets/percentGaugeWidget.js"></script>
    <script>renderWidget();</script>
</html>
&#13;
&#13;
&#13;

0 个答案:

没有答案