渲染存储在列表

时间:2015-11-25 13:43:41

标签: reactjs react-jsx

解释我的问题有点困难,但我会尝试解释我正在尝试做什么和什么不行。

我想根据父组件中的prop值渲染特定组件。该特定组件存储在我有权访问的列表中。

这是ListOfComponents:

let React = require('react');

//List of all components
let Component1 = require("./Component1");
let Component2 = require("./folder2/Component2");
let Component3 = require("./folder2/Component3");


let ListOfComponents = {
    "id1" : {"handler":Component1},
    "id2" : {"handler":Component2},
    "id3" : {"handler":Component3},
};

module.exports = ListOfComponents;

这是我想要渲染不同组件的父组件:

let React = require('react');
let ListOfComponents = require('./ListOfComponents');

let ParentComponent = React.createClass({

    render() {
        let component = ListOfComponents[{this.props.compID}].handler;
        return ( component )
    }
});

module.exports = ParentComponent;

当我尝试运行此操作时,收到错误消息:Invariant Violation: ParentComponent.render() A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object.

这可以完成吗?还是我需要一种不同的方法来根据我的ListOfComponents呈现正确的组件?

1 个答案:

答案 0 :(得分:0)

给定具有此结构的对象:

let ListOfComponents = {
    "id1" : {"handler":Component1},
    "id2" : {"handler":Component2},
    "id3" : {"handler":Component3},
};

要在另一个组件的渲染方法中动态渲染其中一个组件:

render() {
    const Component = ListOfComponents[this.props.compID].handler;
    return <Component />
}

这是一个可运行的例子:

import React from "react"

const Component1 = () => <p>Hello</p>
const Component2 = () => <p>Goodbye</p>

const components = {
  id1: Component1,
  id2: Component2,
}

class App extends React.Component {
  render() {
    const id = "id2"
    const Component = components[id]
    return <Component />
  }
}

export default App