[英]Passing data from rails controller to react component
I'm trying to integrate rails with react via webpacker, but i dont know how to pass in example @post = Post.all
from controller to react component props. 我正在尝试通过webpacker将rails与react集成在一起,但是我不知道如何从控制器中传递@post = Post.all
示例来响应组件道具。 I have to do this by api or there is other way?? 我必须通过api来执行此操作,或者有其他方法吗?
I find solution by my self. 我自己找到解决方案。 https://hackernoon.com/how-to-get-your-rails-data-into-your-react-component-with-webpacker-647dc63706c9 https://hackernoon.com/how-to-get-your-rails-data-into-your-react-component-with-webpacker-647dc63706c9
By adding content tag to view where I want to render react component and pass props as attributes. 通过添加内容标签来查看我要在哪里渲染react组件并将props作为属性传递。
<%= content_tag :div,
id: "appointments_data",
data: @appointments.to_json do %>
<% end %>
then parse data and add it do props 然后解析数据并添加它做道具
document.addEventListener('DOMContentLoaded', () => {
const node = document.getElementById('appointments_data')
const data = JSON.parse(node.getAttribute('data'))
ReactDOM.render(
<Appointments appointments={data} />,
document.body.appendChild(document.createElement('div')),
)
})
Here is another way: 这是另一种方式:
some_views.html.erb some_views.html.erb
<%= javascript_tag do %>
var appointments = <%= raw(@appointments.to_json) %>
<% end %>
some_react_components.js some_react_components.js
document.addEventListener('DOMContentLoaded', () => {
const data = window.appointments
ReactDOM.render(
<Appointments appointments={data} />,
document.body.appendChild(document.createElement('div')),
)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.