如何在 ReactJS 中集成普通(vanilla)JavaScript?

IT技术 javascript reactjs
2021-05-10 09:58:13

我正在尝试将此3D gio 可视化 用于我的 ReactJs 应用程序。代码是用普通的 JavaScript 编写的。我还找到了 React 的包装器并尝试了它,但我无法选择onCountryPicked()他们的演示中显示的所选国家/地区(这是我继续使用 vanilla JavaScript 实现而不是包装器的主要原因。但是,我发现普通 JavaScript 实现很难与我的 ReactJs 应用程序集成。

我环顾四周以解决问题,但我找到的资源对我没有帮助。下面是我去过的一些地方。

helloworld.js

var container = document.getElementById("globalArea");

var controller = new GIO.Controller(container, {
  color: {...},
  brightness: {...},
});

controller.onCountryPicked(callback);
controller.setInitCountry("FR");
controller.showOutOnly(false);
controller.showInOnly(false);

function callback(selectedCountry) {
  $("#countryArea").text(selectedCountry.name + " picked!");
  $("#infoBoard").fadeIn(300);
  setTimeout(function () {
    $("#infoBoard").fadeOut(1000);
  }, 3000);
}

axios
  .get("./test_data.json")
  .then(function (response) {
    controller.addData(response.data);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    controller.init();
  });

var d3Graphs = {
  tiltBtnInterval: -1,
};

function showHud() {
  $("#hudButtons").show();
  $(".tiltBtn").on("mousedown touchstart", d3Graphs.tiltBtnClick);
  $(".tiltBtn").on("mouseup touchend touchcancel", d3Graphs.tiltBtnMouseup);
}

function tiltBtnClick() {
  var delta;
  if ($(this).hasClass("sideViewBtn")) {
    delta = 10;
  } else {
    delta = -10;
  }
  d3Graphs.doTilt(delta);
  d3Graphs.tiltBtnInterval = setInterval(d3Graphs.doTilt, 50, delta);
}

function doTilt(delta) {
  tilt += delta * 0.01;
  tilt = constrain(tilt, 0, Math.PI / 2);
  camera.position.y = 300 * Math.sin(-tilt);
  camera.position.z = 100 + 300 * Math.cos(-tilt);
  camera.lookAt(new THREE.Vector3(0, 0, 300));
  tiltTarget = undefined;
}

………………

主页.html

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <script src="./lib/jquery-3.3.1.min.js"></script>
    <script src="./lib/three.min.js"></script>
    <script src="./lib/gio.min.js"></script>
    <script src="./lib/axios.min.js"></script>
    <script src="https://d3js.org/d3.v5.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
    <link rel="stylesheet" href="helloworld.css" />
  </head>

  <body>
    <div class="b">
      <div id="infoBoard">
        <div id="countryArea"></div>
        <div id="explanation">Infos here</div>
      </div>
      <script src="helloworld.js"></script>
    </div>
  </body>
</html>

…………………………………………………………………………………………………………………………………………

示例.js

export class Sample extends React.Component {
  componentDidMount() {
  
  }

  render() {
    return (
      <div className="App">
         ...
      </div>
    );
  }
}
2个回答

这是一个起点。我已经注释了 React 与 Gio.js 交互的部分。

const Globe = () => {
  // use a React ref whenever you need to directly target a DOM element
  // - this is required as an argument to the GIO.Controller constructor
  const ref = useRef(null);
  const [country, setCountry] = useState(initCountry);

  useEffect(() => {
    // useEffect with empty dependency array
    // - this will run once when the component mounts
    const controller = new GIO.Controller(ref.current, {
      control: {
        initCountry
      }
    });

    // import and add data here if you want the glowing lines
    controller.addData([]);

    controller.init();

    // here's the callback for when the user clicks a country
    // we can use the React setState hook inside the callback
    controller.onCountryPicked((country) => {
      setCountry(country.ISOCode);
    });
  }, []);

  return (
    <>
      <div>
        <strong>Selected country: {displayName.of(country)}</strong>
      </div>
      <div style={{ height: 500 }} ref={ref}></div>
    </>
  );
};

代码沙盒演示

如果您将 vanilla javascript 文件放在与您相同的层次级别index.html并正常链接它,您应该能够在不干扰您的 react javascript 的情况下实现您的 vanilla javascript。只需像往常一样使用<script>标签将其链接到底部即可

或者,useState在你的react代码中使用:

import React, {useState} from "react";
import ReactDOM from "react-dom";

const Country = () => {
  const [country, setCountry] = useState('');

  ///your javascript here

  setCountry(//return from javascript function// );

  return (
     <h1>{country}</h1>
  )
}

ReactDOM.render(<Country/>, document.getElementById("countryArea"));

您需要将 vanilla javascript(例如axios)的任何其他依赖项导入此文件。