在react v15中动态渲染组件

时间:2016-04-26 16:32:31

标签: javascript reactjs ecmascript-6 babeljs

我有一个react components数组,我正在尝试输出它们:

this.props.data

           [
                {
                    key: 1,
                    element: 'input',
                    type: 'text',
                    placeholder: 'Jamie is Sex'
                },
                {
                    key: 2,
                    element: 'input',
                    type: 'text',
                    placeholder: 'Jamie is Not Sex'
                }
           ]

input.component.js

import React from 'react';

const input = React.createClass({
  render() {
    return (
        <input type="text" />
    );
  }
});

export default input;

import components.js

enter image description here

动态代码

import components from '../../componets';
render() {
    return (
        <form action="">
            {this.props.data.map((item, index) => <{components[item.element]} key={index} data={item}/> )}
        </form>
        //{components[item.element]} which would reference 'input' from components.js
    );
}

输出

bundle.js:33283 Uncaught Error: Cannot find module "../components/Form/Form.component.js"webpackMissingModule @ bundle.js:33283(anonymous function) @ bundle.js:33283__webpack_require__ @ bundle.js:20(anonymous function) @ bundle.js:32763__webpack_require__ @ bundle.js:20(anonymous function) @ bundle.js:7464__webpack_require__ @ bundle.js:20(anonymous function) @ bundle.js:48__webpack_require__ @ bundle.js:20(anonymous function) @ bundle.js:40(anonymous function) @ bundle.js:43
bundle.js:99 [WDS] Errors while compiling.

1 个答案:

答案 0 :(得分:0)

您需要通过React.createElement()实际创建元素,jsx会被转换为此语法,但动态元素不会被转换。

我还建议您将映射移出返回,将其映射到变量上,您也可以检查数据的有效性。有点像这样的事情

render() {
    let elems = null;
    let {data} = this.props;
    if(data.length > 0){
        elems = data.map( (item, index) => {
            if(components[item.element]){
                return React.createElement(components[item.element], { key: index, data: item })
            else {
                return null
            }
        });
    }
    return (
        <form action="">
            {elems}
        </form>
    );
}