Symfony UX React
Symfony UX React 是一個整合 React 到 Symfony 應用程式的 Symfony 套件。它是 Symfony UX initiative 的一部分。
React 是一個用於建構使用者介面的 JavaScript 函式庫。Symfony UX React 提供了從 Twig 渲染 React 元件的工具,處理渲染和資料傳輸。
您可以在 Symfony UX React 示範上看到此整合的即時範例。
Symfony UX React 支援 React 18+。
安裝
注意
此套件最適合搭配 WebpackEncore 使用。若要搭配 AssetMapper 使用,請參閱搭配 AssetMapper 使用。
使用 Composer 和 Symfony Flex 安裝套件
1
$ composer require symfony/ux-react
Flex recipe 將自動為您設定,例如將 .enableReactPreset()
新增到您的 webpack.config.js
檔案,並新增程式碼以在 assets/app.js
內載入您的 React 元件。
接下來,安裝一個套件來協助 React
1 2
$ npm install -D @babel/preset-react --force
$ npm run watch
就是這樣!現在可以將 assets/react/controllers/
內的任何檔案渲染為 React 元件。
使用方式
註冊元件
Flex recipe 應該已經將 registerReactControllerComponents()
程式碼新增到您的 assets/app.js
檔案中
1 2 3 4
// assets/app.js
import { registerReactControllerComponents } from '@symfony/ux-react';
registerReactControllerComponents(require.context('./react/controllers', true, /\.(j|t)sx?$/));
這將載入位於 assets/react/controllers
目錄中的所有 React 元件。這些稱為React 控制器元件:旨在從 Twig 渲染的頂層元件。
在 Twig 中渲染
您可以使用 react_component()
函式在您的 Twig 範本中渲染任何 React 控制器元件。
例如
1 2 3 4 5 6
// assets/react/controllers/Hello.jsx
import React from 'react';
export default function (props) {
return <div>Hello {props.fullName}</div>;
}
1 2 3 4 5 6 7 8 9 10 11
{# templates/home.html.twig #}
{% extends 'base.html.twig' %}
{% block body %}
<div {{ react_component('Hello', { fullName: 'Fabien' }) }}>
Loading... <i class="fas fa-cog fa-spin fa-3x"></i>
</div>
{# Component living in a subdirectory: "assets/react/controllers/Admin/OtherComponent" #}
<div {{ react_component('Admin/OtherComponent') }}></div>
{% endblock %}
永久元件
2.21
在 UX React 2.21 中新增了將元件標記為 permanent
的功能。
當從 DOM 中移除根元素時,可以將負責渲染 React 元件的控制器設定為保持 React 元件掛載
,使用 permanent
選項。
當元件的根元素在 DOM 中移動,或被移除並立即重新新增到 DOM 時,這特別有用(例如,當使用
Turbo 及其 `data-turbo-permanent` 屬性時)。
1 2 3 4 5 6 7
{# templates/home.html.twig #}
{% extends 'base.html.twig' %}
{# The React component will stay mounted if the div is moved in the DOM #}
<div {{ react_component('Hello', {fullName: 'Fabien'}, {permanent: true}) }}>
Loading...
</div>
搭配 AssetMapper 使用
由於 JSX 格式不是純 JavaScript,因此搭配 AssetMapper 使用此函式庫需要一些額外步驟。
- 將您的
.jsx
檔案編譯為純 JavaScript 檔案。這可以透過安裝 Babel 和@babel/preset-react
preset 來完成。範例:https://github.com/symfony/ux/blob/2.x/ux.symfony.com/assets/react/build/package.json - 將此函式庫指向包含最終 JavaScript 檔案的 "built" controllers 目錄
1 2 3
# config/packages/react.yaml
react:
controllers_path: '%kernel.project_dir%/assets/build/react/controllers'
此外,在您的 .jsx
檔案中,當匯入另一個元件時,請使用 .js
副檔名
1 2
// use PackageList.js even though the file is named PackageList.jsx
import PackageList from '../components/PackageList.js';
向後相容性承諾
此套件旨在遵循與 Symfony 框架相同的向後相容性承諾:https://symfony.dev.org.tw/doc/current/contributing/code/bc.html