【发布时间】:2016-04-29 21:51:20
【问题描述】:
我已经定义了两个这样的 React 组件:
class CmpA extends React.Component
{ ... }
class CmpB extends React.Component
{ ... }
如您所见,它们是用 ES6 语法定义的。我使用 Webpack 和 Babel 将它们反编译为 ES5。我想要做的是将组件定义存储在变量中,然后渲染它:
render() {
let Cmp = Math.random() > 0.5 ? CmpA : CmpB;
return <Cmp />;
}
但它不起作用,因为上面的代码转换为:
render() {
var Cmp = Math.random() > 0.5 ? CmpA : CmpB;
return _react2.default.createElement('Cmp', {});
}
有人知道如何解决这个问题吗?
[更新]
还请考虑我需要像这样使用Cmp:
render() {
let Cmp = Math.random() > 0.5 ? CmpA : CmpB;
return <div><Cmp /></div>;
}
或者换句话说,我需要能够动态命名组件!
[更新]
这是我项目的 package.json 文件的内容:
{
"name": "expandable-react-redux",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "Mehran",
"license": "ISC",
"dependencies": {
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"react": "^15.0.1",
"react-dom": "^15.0.1",
"react-redux": "^4.4.2",
"redux": "^3.4.0"
},
"devDependencies": {
"babel-core": "^6.7.6",
"babel-loader": "^6.2.4",
"react-hot-loader": "^1.3.0",
"webpack": "^1.12.14"
}
}
【问题讨论】:
-
我在尝试时没有得到
'Cmp'。你确定吗? babeljs.io/repl/… -
代码粘贴在这里,是的,我很确定。也许是因为我在
package.json中使用的依赖项!我将把它包括在我的问题中。 -
一定是打包过程有问题。查看您的
.babelrc和webpack.config.js可能会有所帮助。
标签: reactjs ecmascript-6 webpack babeljs