我已经用6.3.3版初始化了一个新的symfony项目,并想用Reaction来try symfony-UX的东西.所以我遵循了这个指南:https://symfony.com/bundles/ux-react/current/index.html 但是我无法让Reaction组件呈现在页面上.

我已经安装了所有的包,并且有一个如下所示的 struct : enter image description here

然后,我的Controlers.json如下所示:

{
    "controllers": {
        "@symfony/ux-react": {
            "react": {
                "enabled": true,
                "fetch": "eager"
            }
        }
    },
    "entrypoints": []
}

我的bootstrap.js如下所示:

import { startStimulusApp } from '@symfony/stimulus-bridge';
// Registers Stimulus controllers from controllers.json and in the controllers/ directory
export const app = startStimulusApp(require.context(
    '@symfony/stimulus-bridge/lazy-controller-loader!./controllers',
    true,
    /\.[jt]sx?$/
));
// register any custom, 3rd party controllers here
// app.register('some_controller_name', SomeImportedController);

App.js如下所示:

import { registerReactControllerComponents } from '@symfony/ux-react';
import './bootstrap.js';
/*
 * Welcome to your app's main JavaScript file!
 *
 * We recommend including the built version of this JavaScript file
 * (and its CSS file) in your base layout (base.html.twig).
 */

// any CSS you import will output into a single css file (app.css in this case)
import './styles/app.css';

registerReactControllerComponents(require.context('./react/controllers', true, /\.(j|t)sx?$/));

Hello.jsx如下所示:

import React from 'react';

export default function (props) {

   return <div>TESTING</div>;
}

在我的家.html.twig中,我有以下内容:

{% extends 'base.html.twig' %}

{% block body %}
    <div>
        Component should render below
        <div {{ react_component('Hello') }}>
          
        </div>
    </div>
{% endblock %}

而且我在日志(log)中没有得到任何错误,所以安装的模块看起来一切正常.但是Hello.jsx Reaction组件没有显示.只有我在模板中写的其他东西.

然而,当判断时,我可以看到刺激已经将以下内容放到了div开始标签中:

data-controller="symfony--ux-react--react" data-symfony--ux-react--react-component-value="Hello"

但是里面的测试文本不会呈现在页面上.如果有人能帮我看看这个,我会很高兴的:)

顺便说一句,我的Package.json如下所示:

{
    "devDependencies": {
        "@babel/core": "^7.17.0",
        "@babel/preset-env": "^7.16.0",
        "@babel/preset-react": "^7.22.5",
        "@hotwired/stimulus": "^3.0.0",
        "@symfony/stimulus-bridge": "^3.2.0",
        "@symfony/ux-react": "file:vendor/symfony/ux-react/assets",
        "@symfony/webpack-encore": "^4.0.0",
        "core-js": "^3.23.0",
        "react": "^18.2.0",
        "react-dom": "^18.0",
        "regenerator-runtime": "^0.13.9",
        "webpack": "^5.74.0",
        "webpack-cli": "^4.10.0",
        "webpack-notifier": "^1.15.0"
    },
    "license": "UNLICENSED",
    "private": true,
    "scripts": {
        "dev-server": "encore dev-server",
        "dev": "encore dev",
        "watch": "encore dev --watch",
        "build": "encore production --progress"
    }
}

EDIT个 以下是webpack.config的外观:

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

// Manually configure the runtime environment if not already configured yet by the "encore" command.
// It's useful when you use tools that rely on webpack.config.js file.
if (!Encore.isRuntimeEnvironmentConfigured()) {
    Encore.configureRuntimeEnvironment(process.env.NODE_ENV || 'dev');
}

Encore
    // directory where compiled assets will be stored
    .setOutputPath('public/build/')
    // public path used by the web server to access the output path
    .setPublicPath('/build')
    // only needed for CDN's or subdirectory deploy
    //.setManifestKeyPrefix('build/')

    /*
     * ENTRY CONFIG
     *
     * Each entry will result in one JavaScript file (e.g. app.js)
     * and one CSS file (e.g. app.css) if your JavaScript imports CSS.
     */
    .addEntry('app', './assets/app.js')

    // When enabled, Webpack "splits" your files into smaller pieces for greater optimization.
    .splitEntryChunks()

    // enables the Symfony UX Stimulus bridge (used in assets/bootstrap.js)
    .enableStimulusBridge('./assets/controllers.json')

    // will require an extra script tag for runtime.js
    // but, you probably want this, unless you're building a single-page app
    .enableSingleRuntimeChunk()

    /*
     * FEATURE CONFIG
     *
     * Enable & configure other features below. For a full
     * list of features, see:
     * https://symfony.com/doc/current/frontend.html#adding-more-features
     */
    .cleanupOutputBeforeBuild()
    .enableBuildNotifications()
    .enableSourceMaps(!Encore.isProduction())
    // enables hashed filenames (e.g. app.abc123.css)
    .enableVersioning(Encore.isProduction())

    // configure Babel
    // .configureBabel((config) => {
    //     config.plugins.push('@babel/a-babel-plugin');
    // })

    // enables and configure @babel/preset-env polyfills
    .configureBabelPresetEnv((config) => {
        config.useBuiltIns = 'usage';
        config.corejs = '3.23';
    })

    // enables Sass/SCSS support
    //.enableSassLoader()

    // uncomment if you use TypeScript
    //.enableTypeScriptLoader()

    // uncomment if you use React
    .enableReactPreset()

    // uncomment to get integrity="..." attributes on your script & link tags
    // requires WebpackEncoreBundle 1.4 or higher
    //.enableIntegrityHashes(Encore.isProduction())

    // uncomment if you're having problems with a jQuery plugin
    //.autoProvidejQuery()
;

module.exports = Encore.getWebpackConfig();

和base.html.twig:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>{% block title %}Welcome!{% endblock %}</title>
        <link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 128 128%22><text y=%221.2em%22 font-size=%2296%22>⚫️</text></svg>">
        {% block stylesheets %}
        {% endblock %}

        {% block javascripts %}
        {% endblock %}
    </head>
    <body>
        {% block body %}{% endblock %}
    </body>
</html>

推荐答案

您是否使用资源映射器编译了.jsx?我在您的 struct 中看不到编译后的.js文件.

在链接中,https://symfony.com/bundles/ux-react/current/index.html#using-with-assetmapper说的是:

Because the JSX format isn't pure JavaScript, using this library with AssetMapper requires some extra steps.

Compile your .jsx files to pure JavaScript files. This can be done by installing Babel and the @babel/preset-react preset.

此外,我可以看到您在依赖项中使用了webpack-安可. 我们可以看一下您的webpack.config.js和base.html.twig吗? 后面的代码中应该有这样一行代码,用于加载脚本:

{{ encore_entry_script_tags('app') }}

先谢谢你.

(我应该在 comments 中注明我现在没有50名代表:/)

根据webpack的安可文档,您的base.html.twig必须包含

{% block javascripts %}
    {{ encore_entry_script_tags('app') }}
{% endblock %}

以加载该Java脚本文件.然后,您需要将新的.js文件注册到webpack.config.js中,如下所示:

https://symfony.com/doc/current/frontend/encore/simple-example.html#multiple-entries

并将需要的.js文件导入到需要的小枝中(在这里,使用惯性将react 文件导入到需要它的小枝中).这样,就应该执行您的app.js文件.

要编译.js文件,您必须使用以下命令:

npm run watch

要加载css,请使用base.html.twig中的以下代码:

{% block stylesheets %}
    {{ encore_entry_link_tags('app') }}
{% endblock %}

Reactjs相关问答推荐

如何使用json将购物车数组传递到后台API

LocalStore未存储正确的数据

使用setInterval判断数据的时间,然后在过期后从对象中删除;遇到性能问题

如何创建react router v6的自定义子路由?

无法从正在使用Reaction的Electron 商务store 项目中的购物车中删除项目

以下代码是否存在安全问题?

在Map()完成React.js中的多个垃圾API请求后执行函数

获取更改后的状态值

MUiv5和TSS-Reaction SSR问题:无法可靠地处理样式定义.CSSprops 中的ArrowFunctionExpression

使用Ionic 7和React 18,如何访问历史对象以在页面之间导航?

数据表格组件需要所有行都具有唯一的ID属性.或者,您可以使用getRowId属性.

当`useSelector`回调中的属性值更新时,将会使用更新后的值吗?

为什么我会收到此错误:无法在我的react 包上读取 null 的属性(读取useState)?

臭名昭著的测试未包含在 act(...) 中

使用 react pro 侧边栏展开折叠菜单

用 jest 测试包裹在 redux 和 router 中的组件

list 组件未按预期运行

如何将 id 从页面传递到另一个页面?

如何在 react-router-dom v6 中实现监听功能?

如何在 React 中制作动画?