在渲染转储组件时,我目前对容器方法有一个问题。
假设我有一个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}/>
能够传递状态并调用父/容器方法。