【问题标题】:How to render a react component from a string name如何从字符串名称呈现反应组件
【发布时间】:2016-08-08 15:44:18
【问题描述】:

我想从它的字符串名称动态呈现一个反应组件。 这是我所做的,但它不起作用。这可以做到吗?举个例子真的很有帮助。

string_name 是组件的名称。

var MyComponent = React.createElement(window[string_name], {});
return (
      <div className="wrapper">
          <div>Hello World</div>
          <MyComponent/>
      </div>
    )

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    缺少关键位,我不知道它是否记录在任何地方,但是您需要使用大写字母让 JSX 编译器 (?) 将其识别为一种类型。

    import AllComponents from 'Components';
    
    const FooType = 'Foo';
    
    return (
        <div className="wrapper">
            <div>Hello World</div>
            <AllComponents[FooType] />
        </div>
    );
    

    编辑 - 根据 cmets

    class Foo extends React.Component {
        render() { 
            return <div>Foo 123</div>; 
        }
    };
    
    class Bar extends React.Component {
        render() { 
            return <div>Bar 123</div>; 
        }
    };
    
    
    class App extends React.Component {
    
    
      render() {
        const all = {
            'Foo': Foo,
            'Bar': Bar,    
        };
    
        // For the sake of the demo, just randomly pick one of the two
        // usually this would come from an import, or something similar
        const randomKey = ['Foo', 'Bar'][Math.floor(Math.random() * 2)];
    
        // The resolved component must begin with a capital letter
        const Type = all[randomKey];
    
    
        return (
            <div>
                <Type />
            </div>    
        );
      }
    
    };
    
    
    ReactDOM.render(<App />, document.getElementById('root')); 
    

    JSBin:http://jsbin.com/noluyu/5/edit?js,output

    编辑 2

    我们典型的动态渲染组件的应用程序,通常在所有组件目录的根目录下都有一个 index.js 文件,它简单地列出了所有可能的组件:

    // index.js
    export Breadcrumb                from './breadcrumb/Breadcrumb';
    export Checkbox                  from './checkbox/Checkbox';
    export Comment                   from './comment/Comment';
    

    那么你所要做的就是:

    import AllComponents from './index.js';
    
    const myType = 'Checkbox';
    const Type = AllComponents[myType];
    
    .. later ..
    return <div><Type /></div>;
    

    【讨论】:

    • 显然你需要一个可用组件的列表。我将进行编辑,以显示一个内联示例...
    • 但我无法手动列出所有组件。有没有其他方法可以动态地做到这一点。
    • 不,因为它们需要以某种方式导入,否则您的模块加载器(本机,或 browseify 或其他)将永远不会知道将这些模块拉入。我已经再次更新了答案, 以显示此流线型版本
    • 这是一个动态选择组件名称的工作小提琴。如果我在 标签之前写了一些其他的 html 标签,它就不起作用。 jsfiddle.net/geetamamuni/q3zwtosw/19
    • 好的,现在可以了。我接受您的回答,因为这也是一种替代方法。谢谢。
    【解决方案2】:

    您可以做的一件事是在 MyComponent 中要求一个子组件并在返回时呈现它。编写自定义函数以在 Child 中动态呈现组件,然后在 MyComponent 中要求它。

    var React = require('react');
    
    var Names = React.createClass({
      render: function(){
    
        // Map the names and loop through
        var names = this.props.names.map(function(name, index){
    
            return(
                <div> 
                    <li className="list-group-item" key={index}>
                      {<h4>{name[index]}</h4>}
    
                    </li>
                </div>
            )
        });
      }
    });
    
    /*We then export the Names component*/
    module.exports = Names;
    

    下面是父组件。

    var React = require('react');
    var Names = require('./Names');
    
    var MyComponent = React.createClass({
    /*This will set the initial state for any state the component handles. usually empty data*/
     getInitialState: function(){
        return {
    
           names: ["My Component", "Your Component"]
    
        }
     },
    
    
     render: function(){
    
        return(
    
            <div className="row">
    
                <div className="col-md-4">
    
                    <Names names={this.state.names} />
    
                </div>
    
            </div>
        );
     }
    });
    

    【讨论】:

    • 在映射平面字符串数组时,h4 中的 name.name 不会未定义吗?
    • 这是一个动态选择组件名称的工作小提琴。如果我在 标签之前写了一些其他的 html 标签,它就不起作用。 jsfiddle.net/geetamamuni/q3zwtosw/19
    • @GeetanjaliPanda 老实说,有更实用的方法可以解决这个问题。在您的小提琴中,您最终将组件渲染到窗口。您应该将数据作为道具从 Parent 传递给 Child,或 Owner 传递给 Owned,这是 React 方式。然后,您可以编写任何您想要使数据动态显示的自定义函数。
    猜你喜欢
    • 2018-05-22
    • 2021-03-25
    • 1970-01-01
    • 2019-07-22
    • 2020-06-11
    • 2022-08-24
    • 2017-05-12
    • 1970-01-01
    • 2015-06-24
    相关资源
    最近更新 更多