我有一个我想在一些项目中分享/重用的组件.我正在尝试构建/捆绑此组件,因此它不需要通常做出反应的大型设置(webpack/babel/npm/ect).
我想要
就这样.
我觉得我已经非常接近了,但我仍然坚持第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>
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
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'
},
}
Run Code Online (Sandbox Code Playgroud)
尝试使用基本的html渲染组件时,我尝试了很多类似的东西.查看我的调试器,我可以告诉对象是一个与反应类型对象"接近"的东西.我只是不知道该怎么做.
任何指针赞赏
您不应该使用 new 来实例化组件,而应该使用 React.createElement 工厂来实例化它们。因此,您只需将对元素类/函数的引用传递给 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'));
...
Run Code Online (Sandbox Code Playgroud)
顺便说一句,为了简化开发过程中的调试(并且仅在开发过程中!),我建议使用非缩小版本的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>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2473 次 |
最近记录: |