[英]How to make smart components in React even more smarter by making it more flexible rendering other dump components
目前,在渲染轉儲組件時,容器方法存在一個問題。
假設我有一個ProductContainer如下:
class ProductContainer extends React.Component {
constructor(props) {
super(props);
this.state = { products: [] };
}
getAll(){
// get all products from store
}
addNew(){
// store the product to the store
}
render() {
return (
<ListProductComponent products={this.state.products}>
<AddProductComponent/>
)
}
}
我可以使用redux來管理商店,但是在這種情況下,我只想使其盡可能簡單。
然后,我還有兩個轉儲組件,分別為ListProductComponent和AddProductComponent 。
const ListProductComponent = (props) => {
return (
<h2>Print out products from {props.products}</h2>
);
};
const AddProductComponent = (props) => {
return (
<h2>AddProductComponent</h2>
);
};
到目前為止,如此聰明又如此轉儲,但問題在於智能渲染時,如何使智能組件僅渲染ListProductComponent或僅渲染AddProductComponent 。
目前,我在容器的渲染函數中同時顯示了這兩個組件,實際上我想讓容器對Product實體執行CRUD操作,然后將相同的組件用於列出產品,在所有其他轉儲中添加新產品組件。
在當前的實現中,我無法實現這一點,我不得不在同一視圖中同時列出和添加新產品。
有些人建議讓ListProductContainer和addProductContainer分別處理Crud操作,但是這樣分離是否過多? 實際上,我想保留一個智能組件。
如何為智能組件提供更靈活的渲染,以實現這一點。
更新:可能我想在容器上渲染像這樣的部件,但是我不確定這樣的部件是否可行。
function renderComponent(Component) {
return <Component />;
}
然后在容器的render()內部調用此renderComponent,但是如何將狀態/存儲或其他屬性傳遞給轉儲組件?
考慮到我將能夠做這樣的事情:
<ListProductComponent products={products} fetchProducts={this.getAll}/>
能夠傳遞狀態並調用父/容器方法。
如果我理解正確,您是否想有條件地渲染組件? 為此,您將需要在渲染方法中使用三元運算符。
例如:
class ProductContainer extends React.Component {
constructor(props) {
super(props);
this.state = { products: [] };
}
getAll(){
// get all products from store
}
addNew(){
// store the product to the store
}
render() {
return (
{
this.state.products.length ?
<ListProductComponent products={this.state.products}>
:
<AddProductComponent/>
}
)
}
}
添加產品后,您還需要使用this.setState({ products: [ // products object ] })
,以便React重新渲染組件並顯示正確的數據。
您可以在這里了解更多信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.