简体   繁体   English

多次调用同一个实例组件 ReactJS

[英]call a same instance component multiple times ReactJS

I have next modal component in React:我在 React 中有下一个模态组件:

class Modal extends Component {
 render(){
   return(     
    <div className="modal-content">
      <div className="modal-header">
        { this.props.modalHeader }
      </div>
      <div className="modal-body" className={this.props.className}>
        { this.props.modalBody }
      </div>
      <div className="modal-footer">
        { this.props.modalFooter }
      </div>
    </div>);
  }
}

And I'm using it this way:我是这样使用它的:

 render(){

  return(
        <Modal 
           modalHeader={<ContentComponent getSection='header'/>}
           modalBody={<ContentComponent getSection='body'/>}
           modalFooter={<ContentComponent getSection='footer'/>}
        />
  );
 }

There is any way to get a reference of ContentComponent and pass this same reference into the 3 props?有什么方法可以获取 ContentComponent 的引用并将这个相同的引用传递给 3 个道具?

I have tried reference in a constant but doesn't work.我已经尝试在常量中引用但不起作用。

You could create a function that returns a ContentComponent您可以创建一个返回 ContentComponent 的函数

const ccWrapper = (section)=>(<ContentComponent getSection={section}/>)
//later in code
modalHeader={ccWrapper('header')}

If ContentComponent is a function it's even easier:如果 ContentComponent 是一个函数,那就更简单了:

modalHeader={ContentComponent({getSection:'header'})}

You could also let getSection be set by Modal:你也可以让 getSection 由 Modal 设置:

<Modal cc={ContentComponent} />
//in modal
const {cc:ContentComponent} = props;
//...
<div className="modal-header">
  <ContentComponent getSection="header" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM