如何在渲染中使用动态反应 class 元素?

How can I use dynamic react class element in render?

我理解问题不清楚,所以描述会有所帮助。

所以,我有一些反应组件,例如,

var LandingPage = React.createClass({
    render: function() {
        return <div>
            This is the landing page.
        </div>
    }
})

和另一个组件,如

var FirstContent = React.createClass({
        render: function() {
            return <div>
                This is first content page
            </div>
        }
    })

现在我有一个控制器,我可以通过在道具中传递一个值来决定我需要渲染哪个,就像这样 -

var Contoller = React.createClass({
        render: function() {
            var inside = "";
            if (this.props.pageName == "LandingPage") {
                inside = <LandingPage />;
            } else if (this.props.pageName == "FirstContent") {
                inside = <FirstContent />;
            }
            return <div>
                {inside}
            </div>;
        }
    })

现在,我想做一些类似的事情,直接在标签内使用 this.props.pageName,这样我就不必每次都写 if else 广告一些新的替代内容。应该是这样的 -

var Contoller = React.createClass({
        render: function() {
            return <div>
                <"this.props.pageName" /> //comment - <LandingPage /> if this.props.pageName = "LandingPage"
            </div>;
        }
    })

pageName 到实际组件的映射必须存在 某处 ,因为除了默认的 HTML 元素(如 div) React 需要 class 对象引用来渲染组件。字符串不行。

如何管理这张地图由你决定,但我在下面使用了一个对象。

JSX 编译步骤更加复杂,它不适用于动态内容。您必须在 Controller 中使用实际的 JS 调用才能使其正常工作。

这里是 a codepen 演示。

class LandingPage extends React.Component {
  render() {
    return <div> This is the landing page. </div>;
  }
}

class FirstContent extends React.Component {
  render() {
    return <div> This is the first content page. </div>;
  }
}

const map = {
  LandingPage: LandingPage,
  FirstContent: FirstContent
};

class Controller extends React.Component {
  render() {
    return React.createElement(map[this.props.pageName]);
  }
}

React.render(<Controller pageName={'LandingPage'} />, document.body);

综上所述,我认为您正在构建路由器。您可以在 memory mode 中使用 react-router 来执行路由,而无需使用 URL。在这里滚动您自己的设置可能比它值得的更多工作。

地图确实exist in the example by Tyrsius:您可以使用window[this.props.pageName]。尽管最好不要将组件暴露给 window object。如果您将 CommonJS 用于 React 组件,它可能根本不起作用。

如果您不需要构建多个部分的名称,为什么不直接传递组件本身而不是字符串?作为 属性 或者更好的是作为 child:

class Controller extends React.Component {
  render() {
    return <div>{this.props.children}</div>;
  }
}

React.render(<Controller><FirstContent/></Controller>, document.body);