You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React函数组件无法渲染但类组件正常?已解决,求行为解释

更新

在webpack.config.js中将@babel/preset-react的runtime设置为"automatic"后问题解决。runtime默认值为"classic",推测该默认值导致环境无法使用非遗留版React。通过在automatic runtime下成功运行npm run build命令并正常渲染函数组件,已部分验证这一点。

修改后的webpack.config.js配置

presets: [
  [
    "@babel/preset-react",
    {
      runtime: "automatic",
    },
  ],
  "@babel/preset-env",
];

仍希望有人能解释此行为!


问题描述

使用webpack-dev-server和babel-preset-react时,将组件从类组件改为函数组件后,组件不再注册到DOM中;webpack编译成功,但组件无法渲染。希望找到原因并解决,目标是使用函数组件,相关代码如下:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <div id="root"></div>
    
</body>
</html>

index.js(函数组件版)

import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './components/App';

const container = document.getElementById('root');
const root = createRoot(container);
root.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>
);

App.js

export default function App() {
    return (
        <>
            <h1>
                Hello, World!
            </h1>
        </>
    );
}

webpack.config.js(原配置)

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');

module.exports = {

    entry: './src/index.js',

    output: {
        path: path.join(__dirname, '/dist'),
        filename: 'bundle.js'
    },

    plugins: [
        new HTMLWebpackPlugin({
            template: './src/index.html'
        })
    ],

    module: {
        rules: [
            {
                test: /.js$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-react', '@babel/preset-env']
                    }
                }
            }
        ]
    }

}

最初使用的类组件代码如下,修改为函数组件时,已完成将ReactDOM.render()改为createRoot()的必要调整,但修改后热重载的webpack-dev-server无法渲染<App />组件。

index.js(类组件版)

import React, { Component } from 'react';

class App extends Component {

    render() {
        return (
            <>
                <h1>
                    Hello World!
                </h1>
            </>
        )
    }

}

export default App;

内容的提问来源于stack exchange,提问作者gradient_dissent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 16:22:45