【问题标题】:React component render in Django TemplateDjango 模板中的 React 组件渲染
【发布时间】:2021-04-04 07:09:59
【问题描述】:

我有一个 Django 视图,我想通过它呈现一个 React 组件。但无法这样做。这是我的 Django 模板。

{% extends "base.html" %}

{% block javascript %}

    <script>
        window.props = {{props}};  // make sure to escape your props to prevent XSS! See here for the source for the json filter: https://gist.github.com/pirate/c18bfe4fd96008ffa0aef25001a2e88f
        window.react_mount = document.getElementById('react');
    </script>
    <!-- Load React. -->
    <!-- Note: when deploying, replace "development.js" with "production.min.js". -->
    <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js" crossorigin></script>
    <script src="/static/components/{{component}}" type="text/babel"></script>

{% endblock javascript %}

{% block content %}

<div class="container">
    <div class="card">
        <div class="card-body">
          <div id="react">
              <!-- Contents get replaced by mounted React.Component -->
              <i class="fa fa-lg fa-spinner fa-spin"></i><br><br>
              <i class="pending">Loading components...</i><br><br>
          </div>
        </div>
    </div>
</div>

{% endblock content%}

这是我的 React 组件。

import React from 'react'
import ReactDOM from 'react-dom'

class HelloWorld extends React.Component {

    render() {
        return <h1>Hello World!</h1>;
    }

}

ReactDOM.render(
    React.createElement(HelloWorld, window.props),    // gets the props that are passed in the template
    window.react_mount,                                // a reference to the #react div that we render to
)

我收到以下错误:

Uncaught ReferenceError: require is not defined

【问题讨论】:

标签: reactjs django templates


【解决方案1】:

我关注了这个solution 并且它有效。问题是我需要配置捆绑 JS 文件的 webpack(参见 webpack.config.js 文件)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-22
    • 2016-02-21
    • 2016-07-10
    • 2018-05-20
    • 2018-11-05
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    相关资源
    最近更新 更多