代码之家  ›  专栏  ›  技术社区  ›  Mizlul

如何通过更灵活地呈现其他转储组件,使React中的智能组件更加智能

  •  0
  • Mizlul  · 技术社区  · 7 年前

    在渲染转储组件时,我目前对容器方法有一个问题。

    假设我有一个 产品容器 如下所示:

    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 分别地

    目前,我的渲染函数中显示了容器中的两个组件,我实际上希望保留容器来为产品实体执行CRUD操作,然后使用相同的组件列出产品,在所有其他转储组件中添加新产品。

    在目前的实现中,我无法做到这一点,我不得不在同一视图中列出和添加新产品。

    有些人建议让ListProductContainer和addProductContainer分别处理crud操作,但这种方式不是太过分离了吗?实际上,我想把积垢保存在一个智能组件中。

    我如何实现这一点,为非常智能的组件提供更灵活的渲染。

    更新: 也许我想在容器上使用这样的smth渲染部分,但我不确定这样的smth是否有效。

    function renderComponent(Component) {
             return <Component />;
    }
    

    然后在容器上的render()内部调用这个renderComponent,那么如何将状态/存储或其他属性传递给转储组件呢?

    考虑到我也可以这样做:

    <ListProductComponent products={products} fetchProducts={this.getAll}/>
    

    能够传递状态并调用父/容器方法。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Baruch    7 年前

    如果我理解正确,您希望有条件地呈现组件吗?为此,需要在渲染方法中使用三元运算符。

    例如:

    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重新呈现组件并显示正确的数据。

    你可以阅读更多关于它的内容 here

    推荐文章