【发布时间】: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
【问题讨论】:
-
这是 js 错误,但是这部分
src="/static/components/{{component}}以非 django 方式引用静态文件,详情请参阅此答案stackoverflow.com/questions/66437690/…