繁体   English   中英

如何在 index.html 中传递变量以响应组件

[英]How to pass variable in index.html to react components

我正在使用 Django 和 React 制作一个项目。 我从 Django 的 Twitter API 获取数据,我想在前端显示数据。 我将 django views.py 中的数据作为 javascript 变量传递给 index.html。 然后我想在 Components 文件夹中的 Landing.js 中展示它。 我使用了 React 路由器,我的 Landing 和 Main page 是我目前路由到的页面。 我还没有弄清楚如何将数据从单个 html 文件传递​​到 React 中的 Javascript 组件

提前致谢

 <!-- index.html --> <section class="section"> <div class="container"> <div id="app" class="columns"><!-- React --></div> </div> </section> <script type="text/javascript"> window.myVar = "{{context.near.text}}"; //data can be passed from the Django.views.py </script> {% load static %} <script src="{% static 'frontend/main.js' %}"></script>

 //Landing.js js components import React, { Component } from 'react'; class Landing extends Component { componentDidMount() { console.log(window.myVar); //undefined console.log(this.myVVar); //undefined } render(){ return ( <div> </div> ) } } export default Landing;

这是我的树结构

这是我从 Django views.py 传递的上下文

这是我要传递给“LANDING”组件的变量这是“Landing.js”组件我要显示变量

window对象(可能是window._DEFAULT_DATA创建一个新属性,并将其传递给Django中您视图中的序列化数据。

在HTML的head标签中

<script>
    window._DEFAULT_DATA = 'Data parsed in string'
 </script>

然后,当您要使用它时,只需使用JSON.parse即可拥有一个新的JSON。

索引.html:

<script>
localStorage.setItem('data', data)
</script>

反应组件:

let data = localStorage.getItem('data')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM