【问题标题】:JSX - Render code stored in arrayJSX - 渲染存储在数组中的代码
【发布时间】:2018-01-10 10:52:38
【问题描述】:

我有一个问题。如果我将 JSX 代码存储在一个数组中并且它包含

<Accordion uniqId={'addAsset'} 
{...this.props} 
 singleOpen={true} > 
    <AccordionSection title=Asset Summary - Mandatories 
     noFunctions=12 
     noFunctionsDone=0 
     validated={true} 
     required={true} 
     openByDefault={true} > 
         <p>RenderInput</p>
         <p>RenderInput</p>
    </AccordionSection> 
</Accordion>

我从构建它的函数中返回它。函数 parse()。

return JSX;

并尝试像这样在我的组件中使用它。

  render() {
        return(
                <div>
                    <h2>SmartForm Parser</h2>
                    {this.parse(this.props.form)}
                </div>
        );
    }

它没有达到我的预期!它只是将代码作为字符串呈现到屏幕上。如何让它真实呈现!?

编辑 组件内部的完整 parse()

//---------------------------------
class SmartForm extends Component {

// this is a form description parser and renderer.
// it takes the description of a form in JSON format,
// passed in as a prop.


    //-----------------
    constructor(props) {

        super(props);
    }

    //-------------------
    formStart(formType) {

        // each page type in a single or multi page for will have it's own
        // format that has been decreed by the PROPS required by each
        // form initiation.

        let JSX = [];

        console.log('formStart');
        switch(formType) {
            case 'accordion':
                JSX.push("<Accordion");
                JSX.push("  uniqId={'addAsset'}");
                JSX.push("  {...this.props}");
                JSX.push("  singleOpen={true} >");
                console.log('formStart = accordion');
                break;
            case 'workflow':
                break;
            case 'modal':
                break;
            case 'normal':
                break;
        }   
        console.log(JSX);
        return(JSX);
    }

    //-----------------
    formEnd(formType) {

        // each page type in a single or multi page for will have it's own
        // format that has been decreed by the PROPS required by each
        // form initiation.

        let JSX = [];

        switch(formType) {
            case 'accordion':
                JSX.push("</Accordion>");
                break;
            case 'workflow':
                break;
            case 'modal':
                break;
            case 'normal':
                break;
        }    
        return(JSX);
    }

    //-------------------
    pageStart(pageType) {

        // each page type in a single or multi page for will have it's own
        // format that has been designed by the operations management
        // and the CSS designers.

        let JSX = [];

        switch(pageType) {
            case 'accordion':
                       JSX.push(" <AccordionSection ");
                       JSX.push(" title=Asset Summary - Mandatories ");
                       JSX.push(" noFunctions=12");
                       JSX.push(" noFunctionsDone=0");
                       JSX.push(" validated={true} ");
                       JSX.push(" required={true} ");
                       JSX.push(" openByDefault={true} > ");
                break;
            case 'workflow':
                break;
            case 'modal':
                break;
            case 'normal':
                break;

        }
        return(JSX);
    }

    //-----------------
    pageEnd(pageType) {

        // each page type in a single or multi page for will have it's own
        // format that has been designed by the operations management
        // and the CSS designers.

        let JSX = [];

        switch(pageType) {
            case 'accordion':
                JSX.push("</AccordionSection>");
                break;
            case 'workflow':
                break;
            case 'modal':
                break;
            case 'normal':
                break;

        }
        return(JSX);
    }

    //-----------
    parse(form) {

        // this is the main form parser
        // the DESCRIPTION of the for comes into this
        // component as a JSON TREE
        // this parser traverses the tree and constructs the
        // JSX code to be rendered in the calling CONTAINER
        // these few lines of code handle ALL of the forms,
        // in ALL formats, in ALL of the application, from
        // now, until the end of days.

        let JSX = [];                                                       // container for the JSX to be rendered
        let element = '';                                                   // outside field element of form
        let pageElement = "";                                               // page elements
        let fieldElement = "";                                              // each of the field objects in the page
        let formFormat = '';                                                // snatch this value out of tree as we traverse

        console.log(form);

        for (element in form) {                                             // traverse the primary elements
            console.log('----------------------');
            console.log(element);
            switch(element) {                                               // which element are we on?
                case 'formName':                                            // we don't care about the name in here
                    break;
                case 'format':                                              // we DO care about the format!
                    console.log(form.format);
                    JSX.push(...this.formStart(form.format));               // handle the form intro JSX
                    break;
                case 'pages':
                    for (pageElement in form.pages) {                       // iterate for 1..N pages
                        JSX.push(...this.pageStart(form.format));           // depending on the format, each new page gets unique JSX
                        console.log(form.pages[pageElement]);               // debugging
                        let pageArray = form.pages[pageElement];            // Pitman
                        for (fieldElement in pageArray.fields) {            // iterate down the LIST
                            console.log(fieldElement);                      // debugging
                            let fields = pageArray.fields[fieldElement];    // Pitman again
                            JSX.push(...SmartRender(fields));               // and process the field - this does a LOT of work as well!
                        }
                    JSX.push(...this.pageEnd(form.format));                 // finish THIS page
                    }
            }
        }
        JSX.push(...this.formEnd(form.format));                             // finish off the rendering
        console.log(JSX);                                                   // debugging
        return(JSX);                                                        // send back the code for rendering
    }

    //--------
    render() {
        let code = this.parse(this.props.form);
        return(
                <div>
                    <h2>SmartForm Parser</h2>
                    {code.map(function(line, key) {
                        return line;
                        }
                    )}
                </div>
        );
    }
}
//-------------------------------------------------------------------------
export default SmartForm;

//-----------------   EOF -------------------------------------------------

** 第二次编辑 **

//--------------------------
export const assetForm  = {
                            "formName": "assetCreateEdit",
                            "format": "accordion",
                            "pages":
                                [{
                                    "pageID": "1",
                                    "title": "Asset Summary - Mandatories",
                                    "fields":
                                        [
                                            {   
                                                "name": "testname",
                                                "altName": "",
                                                "visible": true,
                                                "groupVisibility": "public",
                                                "type": "text",
                                                "component": "input",
                                                "label": "Test Smart Input",
                                                "placeholder": "Some default Value",
                                                "required": "required",
                                                "validated": false,
                                                "data": []
                                            },
                                            {   
                                                "name": "password",
                                                "altName": "",
                                                "visible": true,
                                                "groupVisibility": "public",
                                                "type": "password",
                                                "component": "input",
                                                "label": "Test Smart Input",
                                                "placeholder": "Password",
                                                "required": "required",
                                                "validated": false,
                                                "data": []
                                            }
                                        ]
                                 },
                                 {
                                    "pageID": "2",
                                    "title": "Asset Images - Mandatories",
                                    "fields":
                                        [
                                            {   
                                                "name": "testname",
                                                "altName": "",
                                                "visible": true,
                                                "groupVisibility": "public",
                                                "type": "imageDrop",
                                                "component": "imageDropbox",
                                                "label": "Test Image Dropbox",
                                                "placeholder": "",
                                                "required": "required",
                                                "validated": false,
                                                "optiminstic": "optomisticPrevire",
                                                "data": []
                                            }
                                        ]
                                 }
                                ]
                            };

干杯, 标记。

【问题讨论】:

  • 不明白,你有codepen吗?
  • 给它一个代码笔有点复杂。
  • hmm,能否提供完整的Parse功能
  • 当然。给我一秒钟,我会把它贴在公共地方。谢谢
  • 我将组件卡在我原来的编辑中。

标签: reactjs react-redux jsx


【解决方案1】:

您不需要将 JSX 渲染为字符串,您可以简单地返回正常的 JSX,如下所示...

你应该能够像这样重构你的代码。

//---------------------------------
class SomeComponent extends Component {
    constructor() {
        super();

        this.state = {
            sampleArray: ["item 1", "item 2", "item 3", "item 4"]
        };

        this.renderExample = this.renderExample.bind(this); // bind this to class method
    }

    renderExample() {
        const { sampleArray } = this.state;

        sampleArray.map((item, index) => {
            return (
                <div className={item} key={item}>
                    {item}
                </div>
            );
        });
    }

    render() {
        return (
            <div id="container">
                {this.renderExample()}
            </div>
        );
    }
}

/*
This would render the following JSX
-----------------------------------
<div id="container">
    <div className="item 1">
        "item 1"
    </div>
    <div className="item 2">
        "item 2"
    </div>
    <div className="item 3">
        "item 3"
    </div>
    <div className="item 4">
        "item 4"
    </div>
</div>
-------------------------------------
HOPE THIS HELPS =]
*/

【讨论】:

  • 谢谢。但是,我的解析器创建的不仅仅是数据项,或者它正在尝试创建!使用您的类比,我的解析器正在生成: sampleArray: ["
    ", "", "
    "] ; 解析器读取一个描述表单的 JSON 对象。所以在解析它之前我不知道表单的结构。干杯!
  • 发布一个可能看起来像这样的 json 样本
  • 在我的原版中。那是对表单内容的描述。表单的结构通过各种机制发生变化,因此我想从描述文件中生成表单的内部。我希望这是有道理的。下一个对象可能有十几个不同的字段。
  • 你应该仍然能够完成你之前所做的所有检查,但不是构建字符串数组,而是返回 JSX
  • 塔! :-) 问题是如何?在解析器中 - p-code 如果 formType == "accordion" 那么输出的开头是 否则输出的开头是
    [构建其余的表单 ...] 如果 formType == "accordion" 那么表单结尾应该是
    否则表单结尾是
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 2021-11-09
  • 2019-10-27
  • 2021-07-31
  • 2018-12-29
相关资源
最近更新 更多