Dynamically Rendering a React component

后端 未结 5 939
暗喜
暗喜 2020-12-04 07:44

In React JSX it does not appear to be possible to do something like this:

5条回答
  •  渐次进展
    2020-12-04 08:30

    If your intention is to inject the actual component rendered, you can do something like this, which is very convenient for testing, or whatever reason you would want to dynamically inject components to render.

    var MyComponentF=function(ChildComponent){
        var MyComponent = React.createClass({
            getInitialState: function () {
                return {
                };
            },
            componentDidMount: function () {
            },
            render: function () {
                return (
                    
    ); } }); return MyComponent; }; var OtherComponentF=function(){ var OtherComponent = React.createClass({ getInitialState: function () { return { }; }, componentDidMount: function () { }, render: function () { return (
    OtherComponent
    ); } }); return OtherComponent; }; var AnotherComponentF=function(){ var AnotherComponent = React.createClass({ getInitialState: function () { return { }; }, componentDidMount: function () { }, render: function () { return (
    AnotherComponent
    ); } }); return AnotherComponent; }; $(document).ready(function () { var appComponent = MyComponentF(OtherComponentF()); // OR var appComponent = MyComponentF(AnotherComponentF()); // Results will differ depending on injected component. ReactDOM.render(React.createElement(appComponent), document.getElementById("app-container")); });

提交回复
热议问题