简体   繁体   English

如何在反应中使用其他js插件?

[英]how to use other js plugin in react?

I've encountered an issue recently where I want to use a 3rd party plugin in my nextjs practice project. 我最近遇到一个问题,我想在我的nextjs实践项目中使用一个3rd party插件。 Please note that I'm a React beginner, therefore, I'm having a hard time wrapping my mind around the 'react way' of doing things. 请注意,我是一个React的初学者,因此,我很难将自己的想法围绕“反应方式”做事。

My problem is that I do not know how to properly initialize/configure a plugin in a project. 我的问题是我不知道如何正确初始化/配置项目中的插件。

For example, I want to use this smoothscroll js plugin. 例如,我想使用这个smoothscroll js插件。 The regular static site approach is to add a script tag in the html files, and then initialize it by calling the plugin. 常规的静态站点方法是在html文件中添加脚本标签,然后通过调用插件对其进行初始化。 eg: 例如:

<script type="text/javascript">
new GambitSmoothScroll({
    amount: 150, // The scroll amount
    speed: 900 // The scroll speed
});
</script>

But in react, this approach does not work because of the virtual DOM. 但实际上,由于虚拟DOM,这种方法不起作用。 Any pointers would be greatly appreciated! 任何指针将不胜感激!

Instead of writing this in your script tag, in your app.js, where you main app is being initialized. 不用在您的script标记中编写此代码,而是在初始化主应用程序的app.js中。 In it's componentDidMount hook add this. 在它的componentDidMount挂钩中添加它。

componentDidMount () {
  new GambitSmoothScroll({
    amount: 150, // The scroll amount
    speed: 900 // The scroll speed
  });
}

I am using here, that you include 'GambitSmoothScroll` at the top of your code. 我在这里使用的是,您在代码的顶部包括“ GambitSmoothScroll”。 In order for this to use. 为了这个使用。

通常我们在React中使用npm或yarn来管理软件包 。在这个特定的第三方中,我建议您阅读本网站的“ 平滑滚动”,您可以在终端中运行它来添加它。

npm install --save smoothscroll

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM