例如,我想要重复使用图书清单组件。在移动设备中由路由使用,在桌面上由另一条路由使用。
图书清单组件包含指向该图书的链接。棘手的部分是桌面版上的书有桌面图书页面网址的链接,而移动版有指向的链接移动图书页面网址。
示例:<BookList type="large" />
示例:<BookList type="small" />
优点:
缺点:
getBookUrl
之类的道具
示例:<BookList getBookUrl={(book)=>
/ small / book / $ {book.id} } />
示例:<BookList getBookUrl={(book)=>
/ large / book / $ {book.id} } />
优点:
缺点:
getBookUrl
(但此功能存储在图书清单组件中),由图书清单组件调用示例:<BookList getBookUrl={BookList.getBookUrlSmall} />
示例:<BookList getBookUrl={BookList.getBookUrlLarge} />
BookList.small = {
getBookUrl: (book)=>`/small/book/${book.id}`,
}
BookList.large = {
getBookUrl: (book)=>`/large/book/${book.id}`,
}
示例:<BookList {...BookList.small} />
示例:<BookList {...BookList.large}/>
答案 0 :(得分:1)
明确配置组件(例如"small"
&amp; "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>