简体   繁体   English

在树枝条件下渲染组件

[英]Render react component with twig conditions

I have backend app in Symfony 3 and I would like process front-end which react. 我在Symfony 3中有一个后端应用程序,我想对它进行反应的前端。 I have two components and I use twig if/else condition to decide witch one will be render 我有两个组成部分,我使用树枝条件/其他条件来决定将要渲染的女巫

{% if some_condition %}
    <div id="compA"></div>
{% else %}
    <div id="compB"></div>
{% endif %}

If/Else working well and components are rendering well too, but every time only one of them... This one which is on first place in index.js 如果/ Else运作良好,并且组件也表现良好,但是每次只有一个...在index.js中排在第一位

import React from 'react';
import ReactDOM from 'react-dom';
import Login from './components/compA';
import Logout from './components/compB';
ReactDOM.render(<compA/>, document.getElementById('compA'));
ReactDOM.render(<compB/>, document.getElementById('compB'));

In this case if "some_conditon" true it renders compA, and if "some_conditon" false nothing happens if I switch last two rows (RenderDOM) CompA nothing happens and CompB working well... And if I do 在这种情况下,如果“ some_conditon”为true,则呈现compA,如果“ some_conditon”为false,则如果我切换最后两行(RenderDOM),则Compa不会发生任何事情,并且CompB可以正常工作。

<div id="compA"></div>
<div id="compB"></div>

Both components are render. 这两个组件都被渲染。 Some idea?? 有想法吗?

Here is what is happening: 这是正在发生的事情:

  1. On the server, Twig PHP evaluates the expression 在服务器上,Twig PHP评估表达式

  2. Either <div id="compA"></div> or <div id="compB"></div> gets generated onto HTML DOM, but not both. <div id="compA"></div><div id="compB"></div>都会在HTML DOM上生成,但不会两者都生成。

  3. The server sends the HTML + JS (React) to the browser 服务器将HTML + JS(React)发送到浏览器

  4. In the browser, the JS tries to do rendering on both #compA and #compB DOM elements. 在浏览器中,JS尝试在#compA#compB DOM元素上进行渲染。

  5. One of the elements is missing, so there will be an error. 缺少元素之一,因此会出现错误。 If the first one is missing, the JS breaks and the second one does not render. 如果缺少第一个,则JS会中断,而第二个则不会渲染。

In index.js, try: 在index.js中,尝试:

if (document.getElementById('compA')) {
    ReactDOM.render(<compA/>, document.getElementById('compA'));
}

if (document.getElementById('compB')) {
    ReactDOM.render(<compB/>, document.getElementById('compB'));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM