load 事件不会等到渲染 react 容器(Firefox 和 Chromium 的区别)

load event doesn't wait till react containers are rendered (difference in Firefox and Chromium)

提问人:Laurent Dhont 提问时间:7/6/2023 更新时间:7/6/2023 访问量:22

问:

我有一个脚本,需要访问 react 渲染的元素。 但是在 firefoxonload 事件中,React 渲染的最后一个元素不可用,而在 Chromium 上则可用。当设置为时,没有问题。webpack modeproduction

下面是一个简化的例子

HTML格式:

<textarea></textarea>
<div class="textAreaContainer"></div>
<textarea></textarea>

<!--This one is not available on firefox-->
<div class="textAreaContainer"></div>

<textarea></textarea>

<!--React script that renders the textareas-->
<script src="react/textAreas.js"></script>
<script>
    window.addEventListener("load", () => {
        const textAreas = document.getElementsByTagName("textarea");
        // The last textarea rendered by React is not available in Firefox
        console.log([...textAreas]);
    });
</script>

反应 (index.js):

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

const containers = document.getElementsByClassName("textAreaContainer");

for (const container of containers) {
    const root = ReactDOM.createRoot(container);

    root.render(
        <React.StrictMode>
            <App />
        </React.StrictMode>
    );
}

反应 (App.js):

import React from "react";
function App() {
  return (
      <textarea name="from-react" cols="30" rows="10"></textarea>
  );
}

export default App;

webpack.config,.js:

const path = require('path');

module.exports = {
    mode: "development",
    entry: {
        textAreas: './react/index.js',
    },
    output: {
        filename: "[name].js",
        path: path.join(__dirname, "public/react")
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader",
                }
            }
        ]
    }
};

.babelrc:

{
  "presets": ["@babel/preset-env", "@babel/preset-react"],
  "plugins": ["@babel/plugin-transform-runtime"]
}

package.json:

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack"
  },
  "keywords": [],
  "author": "Laurent Dhont (LDIT BV)",
  "license": "ISC",
  "dependencies": {
    "@babel/core": "^7.22.6",
    "@babel/plugin-proposal-export-default-from": "^7.22.5",
    "@babel/plugin-transform-runtime": "^7.22.6",
    "@babel/preset-env": "^7.22.6",
    "@babel/preset-react": "^7.22.5",
    "babel-loader": "^9.1.2",
    "babel-preset-react-app": "^10.0.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "webpack": "^5.88.1",
    "webpack-cli": "^5.1.4"
  }
}
JavaScript ReactJS Firefox Chromium 加载

评论


答: 暂无答案