繁体   English   中英

React:一个组件的多个JSX模板

[英]React: multiple JSX templates for one single component

我是一个React新手,我正在开发一个最初使用create-react-app模块创建的React应用程序,我需要使其适应移动设备(浏览器)...为此,我面临的问题是拥有移动设备和相同组件的Web版本。 我想知道是否有一种方法可以通过仅具有2个不同的JSX呈现模板并保持相同的代码库来优化两个单独组件的过程。 我的意思是根据设备加载特定的JSX并将其放置在render方法中。

任何帮助将不胜感激预先感谢

尝试使用响应式库。

您可以基于mediaQuery呈现不同的组件

库参考

import MediaQuery from 'react-responsive';

const Example = () => (
  <div>
    <div>Device Test!</div>
    <MediaQuery query="(min-device-width: 1224px)">
      <div>You are a desktop or laptop</div>
      <MediaQuery query="(min-device-width: 1824px)">
        <div>You also have a huge screen</div>
      </MediaQuery>
      <MediaQuery query="(max-width: 1224px)">
        <div>You are sized like a tablet or mobile phone though</div>
      </MediaQuery>
    </MediaQuery>
    <MediaQuery query="(max-device-width: 1224px)">
      <div>You are a tablet or mobile phone</div>
    </MediaQuery>
    <MediaQuery query="(orientation: portrait)">
      <div>You are portrait</div>
    </MediaQuery>
    <MediaQuery query="(orientation: landscape)">
      <div>You are landscape</div>
    </MediaQuery>
    <MediaQuery query="(min-resolution: 2dppx)">
      <div>You are retina</div>
    </MediaQuery>
  </div>
);

我正在使用Semantic-ui React,并且有一个Responsive组件,您可以呈现广告特定的组件并指定分辨率:例如

<Responsive as={Grid} {...Responsive.onlyMobile} columns='equal' >
   //stuff for mobile
</Responsive>

<Responsive as={Grid} {...Responsive.onlyTablet} columns='equal' >
   //stuff for tablet
</Responsive>

您可以使用Bootstrap之类的东西。 如果这样不能解决问题。 然后,您可以具有一些标志状态,并具有两个返回不同JSX标记的函数。 您将必须编写用于检测Mobile的逻辑。

其他答案取决于屏幕尺寸 (可能导致误报),此解决方案依赖于检测移动设备

您可以使用react-device-detect

<BrowserView>
    <h1> This is rendered only in browser </h1>
</BrowserView>
<MobileView>
    <h1> This is rendered only on mobile </h1>
</MobileView>

这可以在<Switch />内包装单个视图或整个路由集

我们可以使用Rebass库,该库也用于为移动设备,平板电脑和台式机构建响应组件。 我们还可以使用样式化的组件 ,以便我们可以轻松地根据自己的CSS对组件进行样式设置。

https://rebassjs.org/

https://www.styled-components.com/

暂无
暂无

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

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