search

Home  >  Q&A  >  body text

javascript - Virtual DOM manipulation in react components

Explanation: I am a beginner of reactJS;
Requirements are as follows:
1. react component aa.jsx

    var React = require('react');
    var aaa = React.createClass({
        render: function(){
            return (
                <p ref="username" className="comment2">
                    aaaaaaaaa
                </p>
            );
        }
    });
    module.exports = aaa;

2. react component bb.jsx

    var React = require('react');
    var aaa = React.createClass({
        render: function(){
            return (
                <p ref="username" className="comment3">
                    bbbbbbbbbbbbbbb
                </p>
            );
        }
    });
    module.exports = bbb;

3. The main entrance of react, main.jsx, needs to load the required components based on a json file

    json ={
            "data" : [
                {
                    "page" : "aa"
                },
                {
                    "page" : "bb"
                },
                {
                    "page" : "cc"
                }
            ]
        }
    在主函数这里 我用了一个for 循环 
    for (var i=0 ; i< data.length ; i++){
        var page = require('./components/'+ data[i]['page'] +'.jsx');
   }
   

But the problem is, the pages here are all functions. How to take out the dom blocks (p elements) and add them to a specified dom element on the index.html page one by one.

PHPzPHPz2801 days ago949

reply all(2)I'll reply

  • 黄舟

    黄舟2017-05-31 10:42:48

    First of all, what I don’t understand is, since your aa.jsx and bb.jsx are so similar, why do you write two of them (of course, it may be that you wrote the example for convenience). Since they are multiple different files, they are different React components. If you just want to render them all under a certain DOM, just put them directly into an array.

    I haven’t tested the code below, but it should work

    const components = [];
    for (var i=0 ; i< data.length ; i++){
        var Page = require('./components/'+ data[i]['page'] +'.jsx');
        components.push(<Page />);
    }

    Where to embed, JSX code

    <FatherComponent>
        {components}
    </FatherComponent>

    If you want to update it at any time, just re-render it, you can use this.state.components

    You can take a look at our translated React documentation

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-31 10:42:48

    This has nothing to do with virtual dom. Although I don’t know why you use it this way~ but it is wrong if you use it this way!

    reply
    0
  • Cancelreply