如何在刀片模板中使用React js [英] How to use React js in blade template

查看:85
本文介绍了如何在刀片模板中使用React js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将React js用作laravel项目的前端.所以我用以下方式进行了预设:

I would like to use React js as a front-end for my laravel project . So i did the preset with:

php artisan preset react

现在我想知道,应该如何在我的刀片服务器视图中实现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...

例如,在我的homeController中,我传递了一些数据:

For exemple, in my homeController i pass some data:

return views('theview')->with('datas',$datas);

在theview.blade.php中,我可以这样访问它们:

In theview.blade.php i can access them like this:

{{ $datas }}

但是我如何使用它来更新React组件?

but how can i use this to update react component?

推荐答案

从laravel控制器传递数据到React组件的一种方法.
React Component与laravel视图页面上的视图ID元素document.getElementById('example')进行交互. 您的 Laravel Controller 喜欢.

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 Controller like.

class HomeController extends Controller
{
   public function index(){
      $data = [
        'john', 'doe'
      ];
      return view('welcome')->with('data', json_encode($data));
   }
}

确保您传递数据控制器以json形式查看.您的刀片视图

Make sure you passing data controller to view as json. Your Blade View

   ..
   <link rel="stylesheet" href="css/app.css">
</head>
<body>
    <div id="example" data='{{ $data }}'></div>

    <script src="js/app.js"></script>
</body>

您的示例组件,如reources/assets/js/components/Example.js

Your Example Component in reources/assets/js/components/Example.js like

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'));
}

请确保在更改Example.js组件代码时,必须在命令提示符下运行 npm run dev 命令.

Make sure, when you change of Example.js Component code then you must run npm run dev command on your command prompt.

这篇关于如何在刀片模板中使用React js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆