生成现有组件的标签在 ReactJS 中不起作用

Generating Tags of existing components doesn't work in ReactJS

更新

child的编号来自parent,所以我不能只加载这个,这是因为我有很多组件,我不想全部导入.

原始代码已更改post

原版POST

我有很多组件。我想在 parent 组件中动态生成某些 child 组件的标签。我找了这个,发现这应该有效。但由于某种原因它没有..

代码笔:https://codepen.io/anon/pen/qXPReP?editors=0010

class Child1 extends React.Component{
  render() {
    return (
      <div>I'm Child1</div>
    )
  }
};

class Child2 extends React.Component{
  render() {
    return (
      <div>I'm Child2</div>
    )
  }
};

class Child3 extends React.Component{
  render() {
    return (
      <div>I'm Child3</div>
    )
  }
};

class Parent extends React.Component{
  render() {
    var LinkedTag = "Child" + this.props.childIdThatHasToBeRendered;
    return (
      <div>
        <div>i'm the parent</div>
        <LinkedTag />
      </div>
    )
  }
};

class Main extends React.Component{
  render() {
    return (
      <Parent childIdThatHasToBeRendered={3} />
    )
  }
};

ReactDOM.render(<Main />, document.body);

这样可以吗?

只需删除引号

var LinkedTag = Child3;

Child3 是对象,不是字符串

updated codepen

您可以根据条件显示子组件,例如

class Parent extends React.Component{
  render() {
    let component = <Child3/> // Here you can add the code for condition.
    return (
      <div>
        <div>i'm the parent</div>
        {component}
      </div>
    )
  }
};

您需要动态选择要渲染的组件... 您只需要一个宿主对象即可

例如TagRenderers.js:

import Child1 from './child1'
import Child2 from './child2'

export default {
  Child1,
  Child2
}

...稍后

import TagRenderers from '../TagRenderers'

...
render(){
  const TagRenderer = TagRenderers[`Child${this.state.number}`]
  return <div>
    <TagRenderer />
  </div>
}

https://codepen.io/anon/pen/GvMWya?editors=0010

它基本上是从一个对象中挑选一个 属性 - 如果您需要及时需要该组件,它会有所不同 - 这假设它们都在内存中可用

除了@Dimitar Christoff 之外,如果您正在使用 webpack 代码拆分,您可以动态导入这些组件,这样您就不必出于性能原因将它们全部包含在您的包中。

示例:

// childComponent is the name of the component you want to import
const Render = require(`./${childComponent}.jsx`);
return (
// We add ".default" because its importing using the (require) function.
  <Render.default />
);