ReactJS - how create two or more components in same page

扶醉桌前 提交于 2019-12-06 08:39:56

You can just iterate the result from getElementsByClassName:

function renderEls(elements) {
    for (var i = 0; i < elements.length; i++) {
        if( $(elements[i]).attr('comp-url') !== undefined ) {
            var url = $(elements[i]).attr('comp-url');
        }
        ReactDOM.render(<MyMap url={url} />, elements[i]);
    }
}

renderEls(document.getElementsByClassName("MyMap"));

I use jsx with react, you can create a react component that holds all your maps

var MapContainer = React.createClass({
    renderMyMaps: function() {
        return this.props.myMaps.map( function(map, index) {
            return <MyMap url={map.url} widthMap={} heightMap={}/>
            }
        )
    }

    render: function() {
        return (
            <div className="mapContainer">
                { this.renderMyMaps() }
            </div>
        )
    }
})

var MyMap = React.createClass({displayName: "MyMap",
    getDefaultProps: function() {
        return {
            widthMap: 600,
            heightMap: 450
        }
    },
    getInitialState: function() {
        return {
            url: ''
        }
    },
    render: function() {
        return (
            <iframe
                src={this.props.url}
                width={this.props.widthMap}
                height={this.props.heightMap}
                frameborder=0
                allowfullscreen={true} />
        );
    }
});


var maps = [
    {url: '', widthMap: '', heightMap: ''},
    ...
]

ReactDOM.render(<MapContainer myMaps={maps} />,document.getElementById('MyMap'));

with this approach, it might be easier for you to just add to the myMaps property.

you can also just create a container that will output its children.

render(){
    return (
        <div className="MapContainers">
            { this.props.children }
        </div>
    )
 }

the just put all the MyMap that you will create inside MapContainer

<MapContainer>
    <MyMap />
    ...
</MapContainer>

If you are using jQuery (I saw you included it on header), you can do this:

$(".MyMap").each(function() {
    ReactDOM.render(<MyMap url={$(this).attr('comp-url')} />, this);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!