[英]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對組件進行樣式設置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.