创建React Elemets的引用并像Variable一样使用

问题描述

我正在尝试制作一个具有文本和图像并排的简单组件。我试图以这样一种方式来实现它,即根据传递给组件的道具,文本可以显示在右侧,图像显示在左侧,反之亦然。 像这样:

    const TextAndImage = (props)=>{

          let RightComponent;
          let LeftComponent; 

          if(props.align == "text on right and image on left"){

             RighComponent = <p>This is Text</p>                     
             LeftComponent = <img src="source/to/image"/>

          }else{

             RighComponent = <img src="source/to/image"/>
             LeftComponent = <p>This is Text</p>                     
                           
          }
          
          return(
              <Col>
                  <Row> <LeftComponent/> </Row>
                  <Row> <RightComponent/> </Row>
              </Col> 
          )  

   }

如何引用RightComponentleftComponent引用,并以这种方式使用它们。在这里,我使用了<p/><img/>标签。可能会有React元素。

解决方法

您的组件应该是函数,而不是jsx元素。所以:

RighComponent = () => <p>This is Text</p> 
LeftComponent = () => <img src="source/to/image"/>

当需要颠倒顺序时,您还可以使用display: flexflex-direcion: rowflex-direcion: row-reverse的CSS轻松解决此问题