簡體   English   中英

將特定的 React 組件導出到現有的 HTML/JS 項目

[英]Export specific React component to an existing legacy HTML/JS project

我有一個 React 應用程序,我想在現有的遺留(並且非常舊)網頁(不使用任何 JS 框架)中使用這個 React 應用程序中的一個組件。

我試圖做的實際上有點亂,但仍然不起作用:

創建了一個簡單的組件(我想在我的舊應用中展示的那個):

import React from 'react';

const topUserTable = () => {
  return <h1>Top Users</h1>
};

export default topUserTable;

在我的 App.js 中:

const TopUserTable = React.lazy(() => import(/* webpackChunkName: "TopUserTable" */"../components/TopUserTable"));

我的 webpack 輸出 covnfig:

output: {
    path: path.join(__dirname, 'dist'),
    publicPath: 'assets/dist/',
    filename: 'assets/[name].[hash].js',
    chunkFilename: 'assets/[name].[chunkhash].js'
  },

我最終在我的 dist 文件夾中得到了一個以我的組件命名的 JS 文件:

TopUserTable.1ebb44d2d4e148b3973e.js

文件的內容(我認為這並不重要,但為了理智)

(window.webpackJsonp=window.webpackJsonp||[]).push([[3],{"./src/components/TopUserTable.js":function(e,n,s){"use strict";s.r(n);var o=s("./node_modules/react/index.js"),r=s.n(o);n.default=function(){return r.a.createElement("h1",null,"Top Users")}}}]);
//# sourceMappingURL=TopUserTable.1ebb44d2d4e148b3973e.js.map

所以在我的遺留項目中,我確實導入了這個文件和 React:

<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script type="text/javascript" src="assets/TopUserTable.1ebb44d2d4e148b3973e.js"></script>

但是使用標簽什么也沒顯示:

<TopUserTable/>

不確定我缺少什么或我如何能做得更好。 我的目標很簡單:

  1. 在舊版 Web 應用程序中顯示單個 React 組件或
  2. 將我所有的 react 應用程序導入到我的舊項目中,並在任何地方使用所有組件

如何在我的舊應用中顯示我的 React 組件?

謝謝

我沒有看到你的 DOM 容器到你的頁面的 HTML 和對 ReactDOM 的調用。

您需要在舊頁面中(與添加鏈接標簽的位置相同)

<div id="react_app"></div>

並在 app.js 中

const domContainer = document.querySelector('#react_app');
ReactDOM.render(e(TopUserTable), domContainer);

注意:e 實際上是const e = React.createElement;

更多信息在這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM