Laravel 5.5使用来自控制器的数据在刀片视图中渲染React组件 [英] Laravel 5.5 render a React component in a blade view with data from the controller

查看:102
本文介绍了Laravel 5.5使用来自控制器的数据在刀片视图中渲染React组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是能够在刀片视图中执行类似的操作.

My goals is to be able to do something like this in my blade view.

<Example name="{{ $user->name }}" />

但这不会渲染任何东西.

But this doesn't render anything.

当我这样做时:<div id="example"></div>它将呈现没有正常props值的组件.

When I do: <div id="example"></div>it renders the component without the props value which is normal.

所以我试图将来自控制器的数据作为道具传递给我的React组件.

So I am trying to pass data that came from my controller to my React component as a prop.

我不确定是否有可能.

这是我的App.js:

This is my App.js:

require('./components/Example');

这是我的Example.js组件:

This is my Example.js component:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class Example extends Component {
    render() {
        return (
            <div className="container">
                <div className="row">
                    <div className="col-md-8 col-md-offset-2">
                        <div className="panel panel-default">
                            <div className="panel-heading">Example</div>

                            <div className="panel-body">
                                Hello, {this.props.name}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}

if (document.getElementById('example')) {
    ReactDOM.render(<Example />, document.getElementById('example'));
}

推荐答案

例如,我这样做.在index.blade.php

I do it like this eg. in index.blade.php

<div id="main" data-user_name="{{$user->name}}" />

然后在Main.js中

Then in Main.js

const Main = (props) => {
  return (
    <div>
      <Component {...props} />
   </div>
 );
}

if(document.getElementById('main')) {
  const el = document.getElementById('main')
  const props = Object.assign({}, el.dataset)
  ReactDOM.render(<Main {...props} />, el);
}

这篇关于Laravel 5.5使用来自控制器的数据在刀片视图中渲染React组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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