【问题标题】:How to import a component that is rendered in another component?如何导入在另一个组件中呈现的组件?
【发布时间】:2023-03-27 00:36:01
【问题描述】:

我在一个组件component1中渲染了一个form组件,我想在另一个组件component2中使用它,但是我想要将它与它在 component1 中的所有功能一起使用。我怎样才能做到这一点?我尝试从 component1 内部导出它,但它不起作用。

这里是表单组件在component1中渲染的地方:

return (
  <OutsideClickHandler onOutsideClick={this.handleBlur}>
    
     //some not important code was here

      <div
        id={id}
        className={popupClasses}
        ref={node => {
          this.filterContent = node;
        }}
        style={contentStyle}
      >
        {this.state.isOpen ? (
          <FilterForm                           // this FilterFrom I want to export into another component
            id={`${id}.form`}
            paddingClasses={popupSizeClasses}
            showAsPopup
            contentPlacementOffset={contentPlacementOffset}
            initialValues={initialValues}
            keepDirtyOnReinitialize={keepDirtyOnReinitialize}
            onSubmit={this.handleSubmit}
            onChange={this.handleChange}
            onCancel={this.handleCancel}
            onClear={this.handleClear}
          >
            {children}
          </FilterForm>
        ) : null}
      </div>
    </div>
  </OutsideClickHandler>
);

} }

这里是我要导入和使用表单组件的地方

return (
  <div className={classes}>
   
     //some not important code was here
         
    <ModalInMobile
      id="SearchFiltersMobile.filters"
      isModalOpenOnMobile={this.state.isFiltersOpenOnMobile}
      onClose={this.cancelFilters}
      showAsModalMaxWidth={showAsModalMaxWidth}
      onManageDisableScrolling={onManageDisableScrolling}
      containerClassName={css.modalContainer}
      closeButtonMessage={modalCloseButtonMessage}
    >
      
            //here I want to import and use the *form component*


    </ModalInMobile>
  </div>
);

【问题讨论】:

    标签: javascript reactjs forms components react-modal


    【解决方案1】:

    FilterForm 的工作是执行某些逻辑并根据其属性和状态在 DOM 中显示一些元素(就像系统的工作原理一样,您可以停放汽车或让汽车运行两者都是同一个系统,但具有不同的输入和状态)。所以你已经有了你的组件。如果您的意思是 popupSizeClassescontentPlacementOffsetkeepDirtyOnReinitialize、...等属性在组件 1 和组件 2 之间共享,您可以在 FilterForm 周围创建一个包装器,并将这些值传递给 FilterForm。因此,您将改为渲染 FilterFormWrapper 组件。

    但是要确保像onCancel(等于this.handleCancel)这样的一些props是独立的,并且对component1没有任何依赖(状态或props),所以你可以提取它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-17
      • 1970-01-01
      • 2021-03-06
      • 2020-07-23
      • 2020-09-16
      • 2022-10-04
      • 2018-10-31
      • 2020-08-30
      相关资源
      最近更新 更多