【问题标题】:ReactJS - how create two or more components in same pageReactJS - 如何在同一页面中创建两个或多个组件
【发布时间】:2016-02-28 13:38:04
【问题描述】:

我是 ReactJS 的新用户,我遇到了一点问题。我正在创建一个通用地图组件,它运行良好。但是,只能逐页渲染一个组件。我想改用 getElementById,我可以使用 getElementsByClassName

有可能吗?我想保留我的系统通用,我在同一页面中使用许多组件。


在示例中,我使用渲染 1 个地图,但如果我想使用 2 个或更多地图?

<div class="MyMap" comp-url="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3538.7513696363594"></div>
<div class="MyMap" comp-url="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d322231313138.7513696363594"></div>

我想使用:

ReactDOM.render( React.createElement(MyMap, null) , document.getElementsByClassName('MyMap'));

带有 1 个地图示例的代码:

/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};

/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {

/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId])
/******/ 			return installedModules[moduleId].exports;

/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			exports: {},
/******/ 			id: moduleId,
/******/ 			loaded: false
/******/ 		};

/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/ 		// Flag the module as loaded
/******/ 		module.loaded = true;

/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}


/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;

/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;

/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";

/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports) {

	var MyMap = React.createClass({displayName: "MyMap",
	  getDefaultProps: function() {
	    return {
	      widthMap: 600,
	      heightMap: 450
	    }
	  },
	  getInitialState: function() {
	    return {
	      url: ''
	    }
	  },
	  componentWillMount: function() {
	    if ($('#MyMap').attr('comp-url') !== undefined) {
	      this.state.url = $('#MyMap').attr('comp-url');
	    }
	    this.setState({});
	  },
	  render: function() {
	    return (React.createElement("iframe", {src: this.state.url, width: this.props.widthMap, height: this.props.heightMap, frameborder: "0", allowfullscreen: true}));
	  }
	});

	ReactDOM.render( React.createElement(MyMap, null) , document.getElementById('MyMap'));

/***/ }
/******/ ]);
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script src="https://facebook.github.io/react/js/react.js"></script>
  <script src="https://facebook.github.io/react/js/react-dom.js"></script>
</head>

<body>
  <div id="a"></div>
  <div id="MyMap" comp-url="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3538.7513696363594!2d-48.51497268432733!3d-27.508106824924692!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x952746f0c86515b1%3A0xe8ccb33700020efe!2sCorporate+Park!5e0!3m2!1spt-BR!2sbr!4v1448470435091"></div>
</body>

</html>

【问题讨论】:

  • 不如自己试试看有没有问题?
  • 我不明白问题是什么或它与getElementById 有什么关系。请阅读How to Askedit您的问题,以使其更好。
  • 我试过了,还是不行,你知道怎么做吗? @LongNguyen
  • @Nankym 你试过getElementsByClassName 然后遍历所有元素,然后将 React 组件渲染到那个元素中吗?
  • @LongNguyen,我举个例子,看看是否更清楚!

标签: javascript dom reactjs components


【解决方案1】:

您可以只从 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"));

【讨论】:

    【解决方案2】:

    我使用 jsx 和 react,你可以创建一个包含所有地图的 react 组件

    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'));
    

    使用这种方法,您可能更容易只添加到myMaps 属性。

    你也可以只创建一个容器来输出它的孩子。

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

    只需将您将创建的所有 MyMap 放入 MapContainer

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

    【讨论】:

      【解决方案3】:

      如果您使用的是 jQuery(我看到您将它包含在标题中),您可以这样做:

      $(".MyMap").each(function() {
          ReactDOM.render(<MyMap url={$(this).attr('comp-url')} />, this);
      });
      

      【讨论】:

      • getElementsByClassName("MyMap").forEach === undefined 因为它是 NodeList,而不是 Array。
      • 感谢@LongNguyen 的回答!
      猜你喜欢
      • 1970-01-01
      • 2016-04-23
      • 2020-06-19
      • 2019-01-18
      • 1970-01-01
      • 2021-09-22
      • 2017-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多