babelify / transpiling后如何创建和渲染React组件?

时间:2019-05-16 19:00:23

标签: javascript reactjs jinja2 babeljs browserify

我有一个hello world react组件,它用JSX编写,使用babel进行编译,然后包含在Flask应用程序的hello.html模板中。我正在做的工作是在像这样进行编译之前创建和渲染组件:

const hello = <Hello  name="world" />;
ReactDOM.render(hello, document.getElementById('hello'));

如何在hello.html模板的<script>标记中执行上述两个步骤?我的目标是能够将名称变量从模板传递到组件,然后进行呈现。

更多上下文:

JSX hello.js看起来像这样:

import React from 'react';
import ReactDOM from 'react-dom'
import { render } from 'react-dom'

class Hello extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return(
      <div>Hello {this.props.name}!!!</div>
    )
  }
}

//The following works:                                           
//const hello = <Hello  name="world" />;
//ReactDOM.render(hello, document.getElementById('hello'));

hello.html看起来像这样:

<html>
  <head>
  </head>
  <body>
    <div>ASDF</div>
    <div id="hello"></div>
  </body>                           
  {# The following line is a post babelify (transpiled) hello.js #}
  <script type="text/javascript" src="{{ url_for('static', filename='js/hello.js') }}"></script>
  <script type="text/javascript">
    {#
      What goes here? The code in the above section does not work.
      The transpiled code defines a "var Hello = /*#__PURE__*/ function (_React$Component) { ...".
      const hello = Hello(); does not throw an error, but also does not render or pass an argument.
      hello.render(); is also something that I have tried, along with arguments for div/id to render in and name.
    #}
  </script>
</html>

更正:如果脚本为Hello(),则调用text/babel不会引发错误,在这种情况下,脚本可能没有执行任何操作。

烧瓶路线如下:

@app.route(u'/')
def index():
  return render_template(u'hello.html', name="universe")

1 个答案:

答案 0 :(得分:0)

从服务器应用程序传递变量以响应组件的两种方法:

  1. 使用html data-variable属性。

  2. 创建一个全局变量。像window.variable

然后,您应该能够在自己的react-component中以像props.variable之类的道具访问变量。

我推荐的方法是使用捆绑器,例如SystemJS(版本2),您将看到类似以下的内容:

    <!DOCTYPE html>
    <html>
    <head>
        <script src="node_modules/core-js-bundle/minified.js"></script>
        <script src="node_modules/zone.js/dist/zone.js"></script>
        <script type="systemjs-importmap" src="systemjs.imports.json"></script>
        <script src="node_modules/systemjs/dist/system.min.js"></script>
        <script src="node_modules/systemjs/dist/extras/named-exports.min.js"></script>
        <script>
            System.import('../.playground/index.js').catch(function (err) { console.error(err); });
        </script>
    </head>
    <body>
        <div>ASDF</div>
        <div id="hello"></div>
    </body>
    </html>

index.js看起来像这样

ReactDOM.render(
    (< Hello/>),
    document.getElementById('app')
);

然后您的systemjs-importmap将如下所示

{
  "imports": {
    "react": "../node_modules/react/umd/react.production.min.js",
    "react-dom": "../node_modules/react-dom/umd/react-dom.production.min.js",
    // ... other named exports you want to add like the Hello component here
  }
}