简体   繁体   English

如何在 React JS 中使用脚本

[英]How to use scripts in React JS

In my original work I had a <div class="cursor"></div> with this styling:在我的原始作品中,我有一个具有以下样式的<div class="cursor"></div>

.cursor {
    pointer-events: none;
    position: fixed;
    padding: 0.7rem;
    background-color: #fff;
    border-radius: 50%;
    mix-blend-mode: difference;
    transition: transform 0.3s ease;
}

In the script section of my HTML file I have this javascript function for my cursor animation:在我的 HTML 文件的脚本部分,我的光标动画有这个 javascript 函数:

(function () {
    const link = document.querySelectorAll('nav > .hover-this');
    const cursor = document.querySelector('.cursor');
    const animateit = function (e) {
          const span = this.querySelector('span');
          const { offsetX: x, offsetY: y } = e,
          { offsetWidth: width, offsetHeight: height } = this,
          move = 25,
          xMove = x / width * (move * 2) - move,
          yMove = y / height * (move * 2) - move;
          span.style.transform = `translate(${xMove}px, ${yMove}px)`;
          if (e.type === 'mouseleave') span.style.transform = '';
    };
    const editCursor = e => {
          const { clientX: x, clientY: y } = e;
          cursor.style.left = x + 'px';
          cursor.style.top = y + 'px';
    };
    link.forEach(b => b.addEventListener('mousemove', animateit));
    link.forEach(b => b.addEventListener('mouseleave', animateit));
    window.addEventListener('mousemove', editCursor);
})();

How do I change this so it can work within React?我如何更改它以便它可以在 React 中工作?

This is a very broad question but here are a few pointers to get you started...这是一个非常广泛的问题,但这里有一些提示可以帮助您入门......

Start with the React tutorial available from the react site itself at reactjs.org/tutorial/tutorial.html .从 react 站点本身的reactjs.org/tutorial/tutorial.html上的 React 教程开始。 It will cover the basics and also many 'react-y' programming patterns and best practices.它将涵盖基础知识以及许多“反应式”编程模式和最佳实践。

Once you've got that there are a huge number of tutorials available that go much more in depth.一旦你知道了,就会有大量的教程可以更深入地学习。 I would highly recommend Robin Wieruch's stuff: https://www.robinwieruch.de/ (he has also written a number of books on the subject)我强烈推荐 Robin Wieruch 的东西: https ://www.robinwieruch.de/(他还写了一些关于这个主题的书)

Looking at your problem more closely.更仔细地查看您的问题。 I would start by creating a component for the cursor and moving the bulk of the js to that.我将首先为光标创建一个组件并将大部分 js 移动到该组件。 The problem is that without a good grounding in React (or at least the fundamentals) the question you're actually asking is 'How to program in React' rather than 'How do I do this particular thing in React' which would take a lot longer to write an answer to than most of us here on SO have time to do!问题是,如果没有良好的 React 基础(或至少是基础知识),您实际问的问题是“如何在 React 中编程”而不是“我如何在 React 中做这件事”,这需要很多写答案的时间比我们这里的大多数人都长,所以有时间做!

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

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