【问题标题】:React reuse component in both mobile and desktop view移动和桌面视图中的 React 重用组件
【发布时间】:2017-12-18 17:40:38
【问题描述】:

例如,我有一个想要重复使用的书单组件。在移动端被一个路由使用,在桌面被另一个路由使用。

图书列表组件包含图书的链接。棘手的部分是,桌面版上的图书有指向桌面图书页面网址的链接,而移动版有指向的链接手机书页网址

这样做的最佳选择是什么?

1 在图书列表中有一个标志,表明它应该为移动设备或桌面呈现;

示例:<BookList type="large" />

示例:<BookList type="small" />

优点:

  • 易于使用;
  • 简单易做,只需要一些如果没有;

缺点:

  • 不太可重用;

2 传递书籍列表组件调用的getBookUrl等一些props

示例:<BookList getBookUrl={(book)=>/small/book/${book.id}} />

示例:<BookList getBookUrl={(book)=>/large/book/${book.id}} />

优点:

  • 非常可重复使用;

缺点:

  • 很难使用该组件,因为您需要在父级中准备该功能,并且一直这样做很痛苦;

3 传递一些props,如getBookUrl(但该函数存储在书单组件中),由书单组件调用

示例:<BookList getBookUrl={BookList.getBookUrlSmall} />

示例:<BookList getBookUrl={BookList.getBookUrlLarge} />

4 传递书单组件中的一些道具

BookList.small = {
  getBookUrl: (book)=>`/small/book/${book.id}`,
}
BookList.large = {
  getBookUrl: (book)=>`/large/book/${book.id}`,
}

示例:<BookList {...BookList.small} />

示例:<BookList {...BookList.large}/>

5 更好的东西,告诉我 :)

【问题讨论】:

  • 澄清一下,你是在做一个网络应用,对吧?
  • 是的,当然。

标签: reactjs mobile desktop code-reuse


【解决方案1】:

使组件可显式配置(例如"small""large")距离拥有响应式组件(根据屏幕大小自行配置)仅一步之遥。

但是,如果您处理移动设备的策略是(有时)托管一个单独的移动站点,这与移动组件策略背道而驰。

不管怎样,

在不太了解您的具体情况的情况下,我会这样做:

// BookListResponsive.js
import isMobile from "mobile-detector-of-my-choice"
import BookList from "./BookList.js"

export default props => isMobile()
    ? <BookList {...props} getUrl={id => `small/${id}`} />
    : <BookList {...props} getUrl={id => `large/${id}`} />

也许还值得一试 react-routers dynamic routes

<Media query={PRETTY_SMALL}>
  {screenIsSmall => screenIsSmall
    // small screen has no redirect
    ? <Switch>
        <Route exact path="/invoices/dashboard" component={Dashboard}/>
        <Route path="/invoices/:id" component={Invoice}/>
      </Switch>
    // large screen does!
    : <Switch>
        <Route exact path="/invoices/dashboard" component={Dashboard}/>
        <Route path="/invoices/:id" component={Invoice}/>
        <Redirect from="/invoices" to="/invoices/dashboard"/>
      </Switch>
  }
</Media>

【讨论】:

  • 谢谢,这是一个很好的方法,但我不希望组件根据屏幕大小呈现不同的内容。我更喜欢根据道具从上到下清晰地呈现(更易于维护/测试)的内容。
猜你喜欢
  • 1970-01-01
  • 2021-12-04
  • 1970-01-01
  • 2022-11-20
  • 2014-06-25
  • 1970-01-01
  • 2021-05-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多