【问题标题】:Meteorjs + React, how to render several elements in Meteor.startupMeteorjs + React,如何在 Meteor.startup 中渲染几个元素
【发布时间】:2018-11-17 22:08:59
【问题描述】:

我正在尝试声明两个我想渲染的不同 React 元素。这两个元素都是分离的元素,例如显示元素(App.jsx)和自定义帐户系统(Login.jsx)。但在我的测试中,我在两个 jsx 文件中都有相同的代码,以确保问题与它们的特定部分无关。

我还创建了一个 /imports/startup/client/index.js 文件(在 /client/main.js 文件中调用):

import React from 'react';
import { Meteor } from 'meteor/meteor';
import { render } from 'react-dom';

import './accounts-config.js';
import App from '/imports/ui/App.jsx';
import Login from '/imports/ui/Login.jsx';

Meteor.startup(() => {
    render(<App />, document.getElementById('app'));
    render(<Login />, document.getElementById('login'));
})

并且 /client/main.html 包含相关的 div 标签:

...
<div id="app"></div>
<div id="login"></div>
...

问题是第二个渲染永远不会显示(这里是 div 登录),我观察到只有第一个渲染被解释。

我发现的所有示例都只处理单个反应元素。所以我想知道如何像在我的 html 文件中那样使用几个分离的反应元素?

我是 meteorjs 和 react 世界的新手,所以也许我没有得到正确的哲学......

【问题讨论】:

  • AppLogin 渲染到不同的组件中。然后在 Meteor.startup() 中渲染该组件。类似于:render(&lt;NewComponent /&gt;, document.getElementById('app'));

标签: javascript reactjs meteor


【解决方案1】:

您可以使用 React 16 的新功能,即门户。

ReactDOM.createPortal 的使用方法请参考以下链接: How to use ReactDOM.createPortal() in React 16?

【讨论】:

    【解决方案2】:

    我在 Meteor.startup(() (在我的 index.js 中)中仅使用一个渲染解决了我的问题。 React 文档指定只能在 Meteor.startup(() (在我的 index.js 中)中声明一个渲染。 https://reactjs.org/docs/components-and-props.html

    我的代码如下: 在我的 index.js 中

    Meteor.startup(() => {
        render(<App />, document.getElementById('app'));
    })
    

    诀窍是这个超级组件(App.jsx)必须用于调用所有其他组件。在我的示例中,通过调用 Login 组件:

    render() {
        return (
            <div className="container">
                <Login />
            </div>
        )
    }
    

    【讨论】:

      【解决方案3】:

      我相信因为render()语句也有一个隐式的return语句,所以由于它只能执行并返回一个,所以下一个render语句不会被执行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-25
        • 1970-01-01
        • 2018-02-25
        • 2021-12-26
        • 2021-05-01
        • 1970-01-01
        相关资源
        最近更新 更多