发布于 2026-01-06 2 阅读
0

从数据属性调用 React 组件

从数据属性调用 React 组件

动机

我有一个 ASPNET CORE MVC + jQuery 应用程序,需要逐步将一些组件迁移到 React!

既然我们已经从 ViewModel 中获取了数据,我想将其传递给 React 组件。

提议

为什么不使用数据属性呢?
我创建了一个数据属性结构,可以在 React 中读取,并通过它们的属性来调用我的组件(懒加载)。
这样,我就不需要每次都编写 JavaScript 代码来将 'react' 绑定到 HTML 了。

必备条件

  • Webpack
  • Webpack 代码块
  • React

我的数据属性结构

  <div data-js-component="FavoriteButton"
       data-js-props='{
          "favorite": @Model.Document.Favorite.ToString().ToLower()
      }'>
  </div>
Enter fullscreen mode Exit fullscreen mode
  • data-js-component:字符串(要扫描和调用的组件名称)
  • data-js-props:json(初始状态的所有属性)

我的 React 组件

import React from 'react';

export default function FavoriteButton({ favorite }) {
  ...
  ...
}

Enter fullscreen mode Exit fullscreen mode

我的 InvokeComponents:

工作原理

首先,将组件及其各自的路径注册到 `components` 对象中,以便启用延迟导入。
系统会在 HTML 中查找 `[data-js-component]`。找到元素后,会从 `components` 对象中读取其属性。`
[data-js-props]` 将被转换为 JSON 格式,并传递给找到的 React 组件。


import { lazy, Suspense } from 'react';
import ReactDOM from 'react-dom';

const InvokeComponents = (function() {

    //register here your components
    const components = {
        DocumentFavoriteButton: lazy(() => import('./Documents/DocumentFavoriteButton')),
        FavoriteButton: lazy(() => import('./FavoriteButton'))
    }

    const elements = document.querySelectorAll('[data-js-component]');

    for (const element of elements) {
        const { jsComponent, jsProps } = element.dataset;

        const ComponentFound = components[jsComponent];
        let props = JSON.parse(jsProps);

        ReactDOM.render(
            <Suspense fallback={<p>...</p>}>
                <ComponentFound {...props} />
            </Suspense>,
            element
        );

    }
})();

export default InvokeComponents;

Enter fullscreen mode Exit fullscreen mode

现在,在 _layout cshtml 页面上注册您的 InvokeComponent:

<script src="/dist/Components/InvokeComponents.js" asp-append-version="true"></script>
Enter fullscreen mode Exit fullscreen mode

最后,修改你的 webpack.config 文件,使其支持在 lazy 模式下使用 chunk。

  output: {
        path: path.resolve(__dirname, 'wwwroot'),
        publicPath: '/',
        chunkFilename: '[hash].[name].js',
        filename: '[name]'
    },

Enter fullscreen mode Exit fullscreen mode
文章来源:https://dev.to/raafacachoeira/invoke-many-react-components-from-data-attributes-7hf