从Webpack打包的bundle.js导入React组件至HTML页面传参失败求助
问题解决步骤
下面给你梳理核心问题,逐个修正就能解决:
1. 调整CDN引入顺序
当前先加载了bundle.js,但此时React还未被全局引入,必然会导致报错。把bundle.js放到所有CDN脚本之后:
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> <script type="text/babel" src="./build/bundle.js"></script>
2. 修正组件导出与导入逻辑
你的ActionBox是默认导出(export default),且在HTML环境下用全局变量更稳妥。修改Project A的Webpack配置,把组件暴露到全局:
Project A Webpack配置(webpack.config.js)
module.exports = { // ...其他原有配置 output: { // ...其他output配置 library: 'ActionBoxLib', // 定义全局变量名 libraryTarget: 'umd', globalObject: 'this' }, // 将React、ReactDOM设为外部依赖,避免打包进bundle和CDN版本冲突 externals: { react: 'React', 'react-dom': 'ReactDOM' } };
在Project B中直接通过全局变量获取组件:
// 删掉原import语句,替换为全局变量引用 const ActionBox = ActionBoxLib.default;
3. 修复props传递错误
你写的propsData里每个属性都套了多余的对象(比如heading: { heading }会变成heading: { heading: "xxx" }),组件解构后拿到的不是字符串而是对象。修正为:
var propsData = { heading: heading, description: description, variant: variant, color: color }; // 或者用ES6简写: // var propsData = { heading, description, variant, color };
4. 统一React18渲染方式
React18已废弃ReactDOM.render,仅使用createRoot即可,且不要重复渲染。同时注意each循环里的容器元素是当前的section,而非固定id:
// 直接用循环中的this作为容器(即当前的section元素) ReactDOM.createRoot(this).render( React.createElement(ActionBox, { heading, description, variant, color }) ); // 用JSX的写法(需确保Babel能处理): // ReactDOM.createRoot(this).render(<ActionBox {...{ heading, description, variant, color }} />);
5. 修正脚本类型
Project B中的渲染脚本如果用JSX,需设置type="text/babel",完整脚本示例:
<script type="text/babel"> (function ($) { "use strict"; const ActionBox = ActionBoxLib.default; $("[data-component='call-to-action']").each(function () { const color = $(this).data("color"); const description = $(this).data("description"); const heading = $(this).data("heading"); const variant = $(this).data("variant"); ReactDOM.createRoot(this).render( <ActionBox heading={heading} description={description} variant={variant} color={color} /> ); }); })(jQuery); </script>
最后重新打包Project A的组件,刷新Project B页面即可正常渲染并传递props。
内容的提问来源于stack exchange,提问作者SHRIRAM
相关产品推荐
相关产品推荐

