英文:
Can't render react components in my twig templates
问题
我正在构建一个Symfony应用程序。然而,我无法在我的Twig模板中呈现任何React组件。Webpack Encore已安装并正在运行。我已尝试按照他们文档中的所有步骤进行操作 - https://symfony.com/bundles/ux-react/current/index.html。
我已在下面添加了截图和代码。
屏幕上显示的输出是 -
"data-controller="symfony--ux-react--react" data-symfony--ux-react--react-component-value="DepositInputs"
Twig代码 -
<div class="example-wrapper">
{{ react_component('DepositInputs') }}
</div>
app.js代码 -
import '../styles/app.scss';
import { registerReactControllerComponents } from '@symfony/ux-react';
registerReactControllerComponents(require.context('./react', true, /\.(j|t)sx?$/));
DepositInput.js代码 -
import React from 'react';
const DepositInputs = () => {
return (
<div>
<div className="row">
<p>TEST</p>
</div>
</div>
);
}
export default DepositInputs;
文件结构截图 -
composer.json文件 -
我可以使用React的渲染方法,但希望这种本地方法能够工作,因为在我的Twig文件中使用它更容易,并且将Twig变量作为props传递到组件中也更容易!
非常感谢提前提供的任何帮助!我已经为此感到非常困扰!
英文:
i am building a symfony app. However i cannot get any react components to render in my twig template. Webpack encore is installed and running. I have tried going through all steps in their documentation - https://symfony.com/bundles/ux-react/current/index.html.
I have added screenshots and code below.
output i am getting on screen is -
"data-controller="symfony--ux-react--react" data-symfony--ux-react--react-component-value="DepositInputs"
twig code -
<div class="example-wrapper">
{{ react_component('DepositInputs') }}
</div>
app.js code -
import '../styles/app.scss';
import { registerReactControllerComponents } from '@symfony/ux-react';
registerReactControllerComponents(require.context('./react', true, /\.(j|t)sx?$/));
DepositInput.js code -
import React from 'react';
const DepositInputs = () => {
return (
<div>
<div className="row">
<p>TEST</p>
</div>
</div>
);
}
export default DepositInputs;
file structure screenshot -
composer.json file -
I could use the react render method but would like this native method to work as it's much easier to use in my twig files and also easier to pass twig variables down to components as props!
thank you very much in advance for any help offered! I have been pulling my hair out!
答案1
得分: 1
Your react_component([...])
应该在开放的 div
标签内,就像这样:
<div {{ react_component('Admin/OtherComponent') }} >{# 在div中不需要任何内容! #}</div>
而不是在开放和关闭标签之间。 假设您将JS文件放在正确的文件夹中,一切都应该正常工作。 这应该解决了您的问题。 这也是一个好的实践,在div中放一些文本,指示您的组件正在加载。
英文:
Look closely : https://symfony.com/bundles/ux-react/current/index.html#usage
Your react_component([...])
should be in the opening div tag, like this :
<div {{ react_component('Admin/OtherComponent') }} >{# Nothing needed in the div! #}</div>
and not in between the opening and closing tags.
Assuming you put your JS files in the right folders, everything should work properly. This should solve your problem.
It's also good practice to put something in the div, like some text indicating your component is loading.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论