如何在 React Jsx 组件中使用外部 JS/Jquery

问题描述

希望你一切顺利,身体健康。 我是 React.js 的初学者并且正在做我的 FYP 项目,我遇到了一个问题,我无法在 React 中插入外部 JS 或 Jquery 代码, 我在 StackOverflow 中尝试了许多 npm 和提到的流程,但那不起作用? 我应该怎么办?我在哪里导入这些脚本??

解决方法

//import all libraries here   
import React,{ Component } from "react"; //importing react
import $ from "jquery"; // be sure to do npm install jquery
import some_library from "./path/to/some/library"; //importing directly from .js file

class App extends Component {
  render() {
    return (
      ...
    );
  }
}

export default App;

如果您想使用纯 JavaScript/JSON 来呈现其相关的 DOM,我建议您使用功能组件。

import React from "react";

const example = () => {
  return (
    <div className="App">
      <h1>Hello World</h1>
      <h2>This is inside a function</h2>
    </div>
  );
};

export default function App() {
  return example();
}