2017-12-05 18 views
1

ほとんど同じJSX構造を持つコンポーネントがあります。これらの成分は、Panel,SidePanel,CardおよびModalである。ほぼ同じJSX構造のコンポーネントをリファクタリングする方法

私はBEMというCSSクラス名の命名規則と、イベントハンドラ関数と、イベントハンドラ関数がトリガされる場所と方法が異なるため、唯一の違いはclassNameです。

複製されたJSXの使用を防ぐために、これらのコンポーネントをどのようにリファクタリングする必要がありますか?

以下は私のパネルとサイドパネルのコンポーネントJSXから2例、

<div> 
    <article 
     className={classes} 
     id={this.props.id} 
     style={this.props.style} 
    > 
     {title && (
     <div className="panel__title"> 
      <h3>{title}</h3> 
     </div> 
    )} 
     <div className="panel__content">{this.props.children}</div> 
     {toolbarButtons && (
     <footer className="panel__footer">{toolbarButtons}</footer> 
    )} 
    </article> 
    </div> 

サイドパネル、

<div> 
    <article className={classes} id={id} style={style}> 
     {title && (
     <div className="side-panel__title"> 
      <h3>{title}</h3> 
     </div> 
    )} 
     <div className="side-panel__content">{children}</div> 
     {toolbarButtons && (
     <footer className="side-panel__footer">{toolbarButtons}</footer> 
    )} 
    </article> 
    </div> 

であり、あなたはすでにこれらの2つのコンポーネント間の類似性を見ることができます。

答えて

1

あなたがする必要があるのは、css接頭辞を小道具として渡すことだけです。

basePanelを使用することができます。

const basePanel = (props) => (<div> 
    <article className={props.classes} id={props.id} style={props.style}> 
     {title && (
     <div className={`${props.cssPrefix}__title`}> 
      <h3>{props.title}</h3> 
     </div> 
    )} 
     <div className={`${props.cssPrefix}__content`}>{props.children}</div> 
     {toolbarButtons && (
     <footer className={`${props.cssPrefix}__footer`}>{props.toolbarButtons}</footer> 
    )} 
    </article> 
    </div>); 

そして、それが好きで使用します。

あなたのパネルは次のようになります。

const Panel = (props) => <BasePanel {...props} cssPrefix="panel" />; 

あなたのサイドパネルは次のようになります。

const SidePanel = (props) => <BasePanel {...props} cssPrefix="side-panel" />; 
+0

うん、それは私ですしかし、複雑な部分は、これらのコンポーネントのための異なるイベント処理ロジックです。 –

+0

イベントハンドラはどこですか?あなたのコードには表示されません – klugjo

+0

コンポーネントがマウントされた時点で 'document.addEventListener'経由で追加されます –

関連する問題