解决方案可能如下。
带有路由注释的控制器,所有路由都将通过使用此注释来处理,无论路由可能有多少个参数:
namespace App\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Routing\Annotation\Route;
class DefaultController extends Controller
{
/**
* @Template("default/index.html.twig")
* @Route("/{reactRouting}", name="index", requirements={"reactRouting"=".+"}, defaults={"reactRouting": null})
*/
public function index()
{
return [];
}
}
如果您有不应由 react 处理的路由,则您的注释可以将它们排除在外,如下所示 - 所有以 api 开头的路由都不会由 react 处理:
@Route("/{reactRouting}", name="index", requirements={"reactRouting"="^(?!api).+"}, defaults={"reactRouting": null})
带有根元素的 Twig 模板:
{% extends 'base.html.twig' %}
{% block stylesheets %}
<link rel="stylesheet" href="{{ asset('build/js/app.css') }}">
{% endblock %}
{% block body %}
<div id="root"><div>
{% endblock %}
{% block javascripts %}
<script type="text/javascript" src="{{ asset('build/js/app.js') }}"></script>
{% endblock %}
react索引文件:
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
import Home from "./containers/Home";
import AboutUs from "./containers/AboutUs";
ReactDOM.render(
<BrowserRouter>
<Switch>
<Route path="/" component={Home}/>
<Route path="/about-us" component={AboutUs}/>
</Switch>
</BrowserRouter>,
document.getElementById('root'));
我的安可配置:
var Encore = require('@symfony/webpack-encore');
Encore
// the project directory where compiled assets will be stored
.setOutputPath('public/build/')
// the public path used by the web server to access the previous directory
.setPublicPath('/build')
.cleanupOutputBeforeBuild()
.enableSourceMaps(!Encore.isProduction())
// uncomment to create hashed filenames (e.g. app.abc123.css)
// .enableVersioning(Encore.isProduction())
// uncomment to define the assets of the project
// .addEntry('js/app', './assets/js/app.js')
// .addStyleEntry('css/app', './assets/css/app.scss')
// uncomment if you use Sass/SCSS files
// .enableSassLoader()
// uncomment for legacy applications that require $/jQuery as a global variable
// .autoProvidejQuery()
.enableReactPreset()
.addEntry('js/app', './react/index.js')
.configureBabel((config) => {
config.presets.push('stage-1');
})
;
module.exports = Encore.getWebpackConfig();