reactjs – 使用Webpack的独立React组件
发布时间:2020-12-15 05:08:20 所属栏目:百科 来源:网络整理
导读:我有一个我想在一些项目中分享/重用的组件.我正在尝试构建/捆绑此组件,因此它不需要通常做出反应的大型设置(webpack / babel / npm / ect). 我想要 在html页面的某个地方包含来自cdn的React / ReactDOM. 包括我的组件js文件(我们称之为standalone.js). 将一
我有一个我想在一些项目中分享/重用的组件.我正在尝试构建/捆绑此组件,因此它不需要通常做出反应的大型设置(webpack / babel / npm / ect).
我想要 >在html页面的某个地方包含来自cdn的React / ReactDOM. 就这样. 我觉得我已经非常接近了,但我仍然坚持第3项.我无法弄清楚如何将我的组件渲染到DOM. 这是demo html页面的相关部分: index.html(相关部分) <div id="app" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react-dom.min.js"></script> <!--My Component --> <script src="build/standalone.js" type="text/javascript"></script> <script> // I believe I'm doing something wrong here var myComponent = new MyLibrary.default(); var myStandaloneElement = React.createElement(myComponent,{ message: "Testing Standalone Component" }); ReactDOM.render(myStandaloneElement,document.getElementById('app')); </script> standalone.jsx import React,{PropTypes} from 'react'; class Standalone extends React.Component { render() { return <p>{this.props.message}</p>; } } Standalone.PropTypes = { message: PropTypes.string.isRequired } export default Standalone; webpack.config.js(相关部分) var config = { entry: APP_DIR + '/standalone.jsx',output: { library: 'MyLibrary',libraryTarget: 'umd',path: BUILD_DIR,filename: 'standalone.js' },module: { loaders: [ { test: /.jsx?/,include: APP_DIR,loader: 'babel' } ] },externals: { react: 'React',"react-dom": 'ReactDOM' },} 尝试使用基本的html渲染组件时,我尝试了很多类似的东西.查看我的调试器,我可以告诉对象是一个与反应类型对象“接近”的东西.我只是不知道该怎么做. 任何指针赞赏
您不应该使用new实例化组件,而应该使用React.createElement factory实例化它们.所以你只需要将元素类/函数的引用传递给createElement,请参阅yout html的修改部分:
... // get reference to my component constructor var myComponent = MyLibrary.default; var myStandaloneElement = React.createElement(myComponent,{ message: "Testing Standalone Component" }); ReactDOM.render(myStandaloneElement,document.getElementById('app')); ... 另外,为了简化开发过程中的调试(并且只在开发中!)我建议使用非缩小版本的react.js和react-dom.js,它们位于node_modules下,例如: <script src="/node_modules/react/dist/react.js"></script> <script src="/node_modules/react-dom/dist/react-dom.js"></script> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |