laravel 如何在刀片模板中使用 React js
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49843164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use React js in blade template
提问by Barbell
I would like to use React js as a front-end for my laravel project . So i did the preset with:
我想使用 React js 作为我的 laravel 项目的前端。所以我做了预设:
php artisan preset react
Now i would like to know, how react component should be implemented in my blade views so they can access data passed to those views via controllers...
现在我想知道,应该如何在我的刀片视图中实现反应组件,以便他们可以访问通过控制器传递给这些视图的数据......
For exemple, in my homeController i pass some data:
例如,在我的 homeController 中,我传递了一些数据:
return views('theview')->with('datas',$datas);
In theview.blade.php i can access them like this:
在 theview.blade.php 我可以像这样访问它们:
{{ $datas }}
but how can i use this to update react component?
但是我如何使用它来更新反应组件?
回答by Ikram - Ud - Daula
One of this way you pass data from laravel controller to react component.
A React Component interact with view id element document.getElementById('example')
on your laravel viewpage.
Your Laravel Controllerlike.
其中一种方式是将数据从 laravel 控制器传递到反应组件。
React 组件与document.getElementById('example')
Laravel视图页面上的视图 id 元素进行交互。你的Laravel 控制器喜欢。
class HomeController extends Controller
{
public function index(){
$data = [
'john', 'doe'
];
return view('welcome')->with('data', json_encode($data));
}
}
Make sure you passing data controller to view as json. Your Blade View
确保您传递数据控制器以查看 json。你的刀片视图
..
<link rel="stylesheet" href="css/app.css">
</head>
<body>
<div id="example" data='{{ $data }}'></div>
<script src="js/app.js"></script>
</body>
Your Example Componentin reources/assets/js/components/Example.js like
你的示例组件在 reources/assets/js/components/Example.js 中
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
export default class Example extends Component {
constructor(props){
super(props);
console.log('data from component', JSON.parse(this.props.data));
}
render() {
return (
<div className="container">
.....
</div>
);
}
}
if (document.getElementById('example')) {
var data = document.getElementById('example').getAttribute('data');
ReactDOM.render(<Example data={data} />, document.getElementById('example'));
}
Make sure, when you change of Example.js Component code then you must run npm run dev
command on your command prompt.
请确保,当您更改 Example.js 组件代码时,您必须npm run dev
在命令提示符下运行命令。