将js代码集成在react组件中

时间:2016-11-28 10:36:40

标签: reactjs

我已经转换了一个显示图表栏的组件,它需要运行这个js片段,在JSX代码中集成它的正确方法是什么?

<script>
    /** START JS Init "Peity" Bar (Sidebars/With Avatar & Stats) from sidebar-avatar-stats.html **/
    $(".bar.peity-bar-primary-avatar-stats").peity("bar", {
        fill: ["#2D99DC"],
        width: 130,
    })
</script>

我在npm网站上看到了这些库,但它们主要处理外部脚本而不是内部脚本

这是我的组件:

import React, { Component } from 'react';

export default class App extends Component {
  render() {
    return (
    <div>
          "How can I render js code here?" 
     </div>
    );
  }
}

2 个答案:

答案 0 :(得分:1)

您可以使用refscomponentDidMount回调来初始化jquery插件,如此

class App extends React.Component {
  
  componentDidMount() {
    $(this.barChart).peity("bar", { 
      fill: ["#2D99DC"], width: 130
    });
  }
  
  render() {
    return <div>
      <div ref={ (node) => { this.barChart = node }  }>
        <span class="bar">5,3,9,6,5,9,7,3,5,2</span>
        <span class="bar">5,3,2,-1,-3,-2,2,3,5,2</span>
        <span class="bar">0,-3,-6,-4,-5,-4,-7,-3,-5,-2</span>
      </div>  
    </div>;
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/peity/3.2.1/jquery.peity.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="container"></div>

答案 1 :(得分:1)

您应该使用componentDidMount lifecycle hook。 将其添加到组件代码中:

componentDidMount() {
 $(".bar.peity-bar-primary-avatar-stats").peity("bar", {
        fill: ["#2D99DC"],
        width: 130,
    })
}