React + Webpack + ES6中的动态组件名称

时间:2016-04-29 21:51:20

标签: reactjs ecmascript-6 webpack babeljs

我已经定义了两个这样的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', {});
}

有谁知道如何克服这个问题?

[UPDATE]

还请考虑我需要像这样使用Cmp

render() {
    let Cmp = Math.random() > 0.5 ? CmpA : CmpB;
    return <div><Cmp /></div>;
}

或者换句话说,我需要能够动态命名一个组件!

[UPDATE]

这是我的项目的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"
  }
}

1 个答案:

答案 0 :(得分:2)

我相信你可以这样做:

render() {
    const props = { prop1: 10 };
    let Cmp = Math.random() > 0.5 ? <CmpA {...props} /> : <CmpB {...props} />;
    return <div>{Cmp}</div>; 
}