首页 > 解决方案 > symfony 中的集成模板 reactjs

问题描述

我在我的 Symfony 应用程序中集成模板 reactjs。但是,当我运行我的应用程序时,我的应用程序显示一个空白页面。

请帮我!

我正在使用 symfony4 并将 js 与 webpack encore 反应。

这是我的 layout.html.twig:

      <!DOCTYPE html>
         <html>
          <body>
            {% block body %}
             <div id="root"></div>
              {% endblock %}
              {% block javascripts %}
              <script type="text/javascript" src="/build/js/temp.js"> 
              </script>
        {% endblock %}
        </body>
        </html>   

这是我的控制器:

 <?php
  namespace App\Controller;
       use Symfony\Bundle\FrameworkBundle\Controller\Controller;
        use Symfony\Component\HttpFoundation\Response;
        use Symfony\Component\Routing\Annotation\Route;
        final class HomeController extends Controller
        {

        public function home(): Response
        {
    return $this->render('layout.html.twig');
         }
         }

我的 Webpack.config.js:

 var Encore = require('@symfony/webpack-encore');

 Encore

.setOutputPath('public/build/')

.setPublicPath('/build')
.addEntry('js/main', './assets/js/main.js')
.addEntry('js/temp', './assets/js/temp.js')
.addStyleEntry('css/util', './assets/css/util.css')
.addStyleEntry('css/material-dashboard-react', './assets/css/material- 
 dashboard-react.css')
.addStyleEntry('css/main', './assets/css/main.css')
.cleanupOutputBeforeBuild()
.enableBuildNotifications()
.enableSourceMaps(!Encore.isProduction())
// enables hashed filenames (e.g. app.abc123.css)
.enableVersioning(Encore.isProduction())
.configureBabel(function(babelConfig) {
  babelConfig.presets.push('env');
})
.enableReactPreset();
;

module.exports = Encore.getWebpackConfig();

我在 assets/js/temps.js 中集成模板 reactjs。在 temp.js 中:

 js
 ¦___temp.js
          ¦__components
          ¦__Containers
          ¦__routes
          ¦__variables
          ¦__views
          ¦__index.js

这是我的 index.js:

 import React from 'react';
 import ReactDOM from 'react-dom';
 import { createBrowserHistory } from 'history';
 import {
   Router,
   Route,
   Switch
} from 'react-router-dom';

import '../../css/material-dashboard-react.css';

import indexRoutes from './routes/index.jsx';

const hist = createBrowserHistory();

ReactDOM.render(
<Router history={hist}>
    <Switch>
        {
            indexRoutes.map((prop,key) => {
                return (
                    <Route path={prop.path} component={prop.component}  key= 
{key}/>
                );
            })
        }
    </Switch>
</Router>
, document.getElementById('root'));

标签: javascriptreactjswebpacksymfony4react-dom

解决方案


我认为你应该试试这个:

  • 构建你的反应项目
  • 将捆绑的脚本和 css 从 build/static/ 放置到适当的目录
  • 在模板中加载它

你也应该从你的模板中评估 ReactDOM.render


推荐阅读