我一直在寻找这个问题,但仍然不是很清楚。您使用什么方法使用 Reacjs 为 Django 应用程序构建模板?如何为授权用户和非授权用户显示不同的菜单?是否可以将 html 布局保留在 .html 文件中,只在需要的地方呈现 Reactjs 组件?这些组件之间如何通信?
例如:
我有一个这样的页面,带有菜单和项目列表:
<body>
<div>
{% if not user.authenticated %}
<a href="/login">Login</a>
{% else %}
<a href="/logout">Logout</a>
<a href="#">Add item</a>
{% endif %}
</div>
<ul>
<li>One</li>
<li>Two</li>
</ul>
</body>
如果用户未被授权,我会在其中显示一个按钮“登录”,否则有两个按钮:“注销”和“添加项目”。当我单击“添加项目”按钮时,我需要打开带有表单的模式窗口。在表单提交上,我想将项目附加到 <ul>
列表。这只是示例,页面可以包含很多 html 标记。以上问题。
如果我的问题不清楚,请在评论中提问。
最佳答案
我认为你有点困惑,如果你正在使用 React(或任何其他用于单页应用程序的 js 框架),你不应该使用 django 模板来渲染某些部分(即使你可以)。显示或不显示登录的逻辑应该在react模板中,而不是在django模板中。例如: Django 模板
<head>
<script>
var userInfo = {
authenticated : {% user.authenticated %}
// add anyother user info
}
</script>
<head>
<body>
<div id="app"/>
</body>
JS应用:
var React = require("react");
var Component = require("./components/Login");
function render(element, id) {
React.render(<Login/>, document.getElementById(id));
}
render(Component, "app");
登录:
var React = require("react");
var Login = React.createClass({
renderLogin: function () {
var loginButton;
if (userInfo.authenticated) {
loginButton = <LogoutButton />;
} else {
loginButton = <LoginButton />;
}
return loginButton;
}
render: function() {
return (
<div className="Login">
{renderLogin}
</div>
</div>
);
}
});
module.exports = Login;
我不只是从任何 React 组件访问全局变量,而是从根组件访问它,然后通过 props 或上下文将它传播到子组件。
关于javascript - Django 和 Reactjs : complex templates,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35154234/