问题
I have managed to render my component on a div on my template like so:
Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body>
{% load render_bundle from webpack_loader %}<h1>Example</h1>
<div id="react-app"></div>
{% render_bundle 'main' %}
</body>
</html>
My react app:
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
const rootElement = document.getElementById('react-app');
ReactDOM.render(<App />, rootElement);
Whats a good approach to pass in data to react? i'm using Django templates
回答1:
It is possible to pass props to the root element through data attributes and pass them to root element in index.js
<div
id="root"
data-custom-props='{aKey: "a value"}'
></div>
index.js file:
ReactDOM.render(<App {...(root.dataset)}/>, root);
回答2:
A common pattern is to output a json string into a script tag, which you can then refer to in your init function.
For example:
// Above where you include your main bundle
<script>
window.__INITIAL_STATE.__ = { your: 'DATA', encodedIn: 'json', here: true }
</script>
You can then reference window.__INITIAL_STATE__
in your index.js and pass data as props into your root component.
回答3:
What data do you want to pass to react? Props is the concept that allow user to pass data from one component to another within react. It is not made to pass data from outside world to react app.
I believe this answer can guide you in right direction. How to get Django and ReactJS to work together?
also read following to get some idea of back-end and front-end working together. http://geezhawk.github.io/using-react-with-django-rest-framework http://www.openmindedinnovations.com/blogs/3-ways-to-integrate-ruby-on-rails-react-flux
来源:https://stackoverflow.com/questions/43847077/how-to-pass-props-from-template-to-react-root-node