javascript - 在 React 应用程序中使用 vanilla JavaScript 包

标签 javascript reactjs

我的目标是在更复杂的 React 应用程序中使用 Vanilla JavaScript 包来围绕 JavaScript 包构建额外的逻辑。

JavaScript 库是 LabelStudio,可在此处找到文档:https://github.com/heartexlabs/label-studio-frontend

但是,当我尝试导入 LabelStudio 时,出现错误提示 Module not found: Can't resolve 'label-studio' ,如此处所述 https://github.com/heartexlabs/label-studio-frontend/issues/55

由于我对前端代码的了解有限,我不确定这是否是开发人员不希望用户做的,只是希望他们使用整个库并进行自定义,而不是将库作为一个组件使用。我的想法是像这里的 vanilla javascript 示例一样使用该库:

<!-- Include Label Studio stylesheet -->
<link href="https://unpkg.com/label-studio@0.7.1/build/static/css/main.0a1ce8ac.css" rel="stylesheet">

<!-- Create the Label Studio container -->
<div id="label-studio"></div>

<!-- Include the Label Studio library -->
<script src="https://unpkg.com/label-studio@0.7.1/build/static/js/main.3ee35cc9.js"></script>

<!-- Initialize Label Studio -->
<script>
  var labelStudio = new LabelStudio('label-studio', {
    config: `
      <View>
        <Image name="img" value="$image"></Image>
        <RectangleLabels name="tag" toName="img">
          <Label value="Hello"></Label>
          <Label value="World"></Label>  
        </RectangleLabels>
      </View>
    `,

    interfaces: [
      "panel",
      "update",
      "controls",
      "side-column",
      "completions:menu",
      "completions:add-new",
      "completions:delete",
      "predictions:menu",
    ],

    user: {
      pk: 1,
      firstName: "James",
      lastName: "Dean"
    },

    task: {
      completions: [],
      predictions: [],
      id: 1,
      data: {
        image: "https://htx-misc.s3.amazonaws.com/opensource/label-studio/examples/images/nick-owuor-astro-nic-visuals-wDifg5xc9Z4-unsplash.jpg"
      }
    },
    
    onLabelStudioLoad: function(LS) {
      var c = LS.completionStore.addCompletion({
        userGenerate: true
      });
      LS.completionStore.selectCompletion(c.id);
    }
  });
</script>   

如何在 React 组件中使用上述代码来实现动态数据加载和使用状态来自定义功能?

最佳答案

我没有使 npm 模块 label-studio 工作的解决方案。我尝试导入 dist file相反,但它会出错

Expected an assignment or function call and instead saw an expression

在维护者解决这个问题之前,这是一个解决方法。

build/static/js复制JS文件,然后将它放在 index.html 上公共(public)文件夹中的脚本中

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="theme-color" content="#000000" />
  <meta name="description" content="Web site created using create-react-app" />
  <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
  <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
  <title>React App</title>
</head>

<body>
  <noscript>You need to enable JavaScript to run this app.</noscript>
  <div id="root"></div>
  <script src="%Your_Path_To_Label-Studio%/main.js"></script>
</body>

</html>

脚本文件定义了一个全局函数变量,因此您可以在 React 中使用 window 对象访问它。 useEffect Hook 是为了确保初始化只运行一次。

import React, { useEffect, useRef } from "react";

function App() {
  const LabelStudio = window.LabelStudio; // label-studio script stores the api globally, similar to how jQuery does
  const myLabelStudioRef = useRef(null); // store it and then pass it other components

  useEffect(() => {
    myLabelStudioRef.current = new LabelStudio("label-studio", {
      config: `
      <View>
        <Image name="img" value="$image"></Image>
        <RectangleLabels name="tag" toName="img">
          <Label value="Hello"></Label>
          <Label value="World"></Label>  
        </RectangleLabels>
      </View>
    `,

      interfaces: [
        "panel",
        "update",
        "controls",
        "side-column",
        "completions:menu",
        "completions:add-new",
        "completions:delete",
        "predictions:menu",
      ],

      user: {
        pk: 1,
        firstName: "James",
        lastName: "Dean",
      },

      task: {
        completions: [],
        predictions: [],
        id: 1,
        data: {
          image:
            "https://htx-misc.s3.amazonaws.com/opensource/label-studio/examples/images/nick-owuor-astro-nic-visuals-wDifg5xc9Z4-unsplash.jpg",
        },
      },

      onLabelStudioLoad: function (LS) {
        var c = LS.completionStore.addCompletion({
          userGenerate: true,
        });
        LS.completionStore.selectCompletion(c.id);
      },
    });
  }, []);

  return (
    <div className="App">
      {/* Use Label Studio container */}
      <div id="label-studio"></div>
    </div>
  );
}

export default App;

就存储 LabelStudio 的新实例而言,有很多方法可以解决。您可以使用 useStateuseRef Hook 将其作为变量存储在根组件上,然后将其传递给子组件。如果你想避免手动将变量传递到组件树下,那么你需要一个状态管理器,例如 React Context或 Redux。

关于javascript - 在 React 应用程序中使用 vanilla JavaScript 包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62801255/

相关文章:

javascript - 如何使用 ReactJs 中的 dropzone 将文件及其描述添加到状态?

javascript - 获取倒数第二个和最后一个斜杠之间的内容

javascript - 使用 HTML/CSS/JQuery 实现 WYSIWYG 报表生成器?

reactjs - 警告 : findDOMNode is deprecated in StrictMode, react-redux-notify

javascript - 单独的 ApolloProvider 组件渲染与 ReactDOM 给出错误

reactjs - 使用 setTimeout() 调用 Redux 操作

javascript - 如何处理浏览器中显示数据的重负载处理

javascript - 如何根据内部数据自动调整 Bootstrap 列宽度

javascript - 将工具提示添加到流程图

css - 边界半径意外地不均匀