[英]Approach for different HTML structure with React and using the same components
我应该选择哪条路径来制作一个应该有两个不同视图的应用程序。 一种用于移动设备,一种用于桌面和 CSS Media Queries 不足以解决这种冷漠问题。
任何建议或指导表示赞赏。 我试图研究,但没有运气,所以文档在哪里处理这个问题,以及其他来源如何处理这个问题。
我想我可以使用 vanilla JS 并直接操作 DOM,但这几乎失去了 React 的目的。
你尝试过类似 react-device-detect 的东西吗?
https://www.npmjs.com/package/react-device-detect
您可以有两种不同的布局,如下所示:
<BrowserView>
<h1> This is rendered only in browser </h1>
</BrowserView>
<MobileView>
<h1> This is rendered only on mobile </h1>
</MobileView>
如何为您的每个组件创建 2 种渲染方法,一种用于移动设备,一种用于桌面。
当用户进入您的应用程序时,获取其device info
并将全局视图状态分配为1
(移动)和2
(桌面)。 之后,根据您的视图状态道具和基本条件检查渲染您的组件。
class App extends React.Component {
constructor(props) {
super(props);
this.state = { view: this.props.view }; // "1" or "2"
}
render() {
if (this.state.view === "1") {
return (
// mobile ui
);
} else {
return (
// desktop ui
);
}
}
}
您可以在此处找到有关 React 条件渲染的更多信息。
还有一个想法:您可以将您的应用程序拆分为 2 个不同的顶级组件。 如果您使用的是 react-router,谁没有 :),在您获得用户的设备信息后,您可以像这样重定向它们:
应用程序.js
<Switch>
<Route path="/" name="Redirect" component={Redirect}/>
<Route path="/mobile" name="Redirect" component={Mobile}/>
<Route path="/desktop" name="Redirect" component={Desktop}/>
</Switch>
重定向组件
render() {
if (getDeviceInfo === "1")
return (<Redirect to={"/mobile"}/>);
else
return (<Redirect to={"/desktop"}/>);
}
通过这种方式,您无需保留组件的 2 个不同 ui。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.