具有next.js的类的新实例不起作用

时间:2018-12-16 13:10:45

标签: javascript next.js

我正在尝试在next.js应用程序中使用js轮播(siema),但无法使其正常工作。无论尝试如何,我都会出错。

我有一个名为HomeSlideShow.js的幻灯片组件:

import Head from "next/head";
import Siema from "../.next/static/js/siema";

const HomeSlideShow = props => (
 <div>
   <Head>
    <script type="module" src="_next/static/js/siema.js" />
  </Head>
  <div className="siema">
    <div>Hi, I'm slide 1</div>
    <div>Hi, I'm slide 2</div>
    <div>Hi, I'm slide 3</div>
    <div>Hi, I'm slide 4</div>
  </div>
</div>
);

export default HomeSlideShow;

我正在将组件导入index.js文件:

import HomeSlideShow from "../components/HomeSlideShow";

const Index = props => (
  <Layout>
   <HomeSlideShow />
  </Layout>
);

我只是不知道如何使用以下方法初始化滑块:

new Siema();

或者:

<script>
 new Siema();
</script>

根据文档。无论我在哪里尝试,都会出错。有指针吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

我认为您需要将功能组件转换为类组件,并尝试在componentDidMount lifycycle method as it is executed after initial render内初始化siema插件

import Head from 'next/head';
import Siema from '../.next/static/js/siema';

class HomeSlideShow extends React.component {
  componentDidMount() {
    new Siema();
  }

  render() {
    return (
      <div>
        <Head>
          <script type="module" src="_next/static/js/siema.js" />
        </Head>
        <div className="siema">
          <div>Hi, I'm slide 1</div>
          <div>Hi, I'm slide 2</div>
          <div>Hi, I'm slide 3</div>
          <div>Hi, I'm slide 4</div>
        </div>
      </div>
    );
  }
}

export default HomeSlideShow;

希望这会有所帮助!