【问题标题】:Dynamic component names in React + Webpack + ES6React + Webpack + ES6 中的动态组件名称
【发布时间】: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 中使用的依赖项!我将把它包括在我的问题中。
  • 一定是打包过程有问题。查看您的.babelrcwebpack.config.js 可能会有所帮助。

标签: reactjs ecmascript-6 webpack babeljs


【解决方案1】:

我相信你可以这样做:

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

【讨论】:

  • 你的答案是正确的,但不是我要找的东西!我更新了我的问题以更好地反映我的问题。
  • 更新了答案以匹配您的问题。
  • 谢谢,但我也可以为{Cmp} 设置属性吗?喜欢{Cmp prop1="10"}
  • 您可以使用扩展运算符代理道具:&lt;CmpA {...props} /&gt;
猜你喜欢
  • 2015-05-04
  • 2015-07-04
  • 2015-07-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多