2016-05-04 12 views
1

リアクションのレンダリングメソッドでは、配列をループして結果の要素をレンダリングする場合、あらかじめ定義されたstyleオブジェクトと依存するスタイルコンポーネントのレンダリング時にmapコールバックで提供される引数についてリアクションコンポーネントのインラインスタイルとあらかじめ定義されたスタイルをレンダリングする

class Example extends React.Component { 
    render() { 

    const otherStyles = { 
     height: '20px', 
     backgroundColor: 'blue' 
    } 

    return (
     {this.props.items.map((d, i) => { 
     return (
      // also include otherStyles 
      <div style={{width: i * 10 + '%'}}></div> 
     ) 
     }} 
    ) 
    } 
} 

私は戻り値としてインラインスタイルのすべてを置くことを避けるのが好きではなく、唯一のmapコールバックからの引数に依存してこれらのスタイルを宣言するだろう。

ループ内でコンポーネントをレンダリングするときに、インラインスタイルと組み合わせて追加のスタイルオブジェクトを含める方法はありますか?

+1

Object.assign:

{ height: '20px', backgroundColor: 'blue', width: '10%' } 

は具体的には、私は以下のrenderメソッドで両方のオプションを置きます。 https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/assign –

+0

これはObject.assignの完璧な使用例です。ありがとうございます! – Himmel

答えて

0

ES6には2つの素晴らしいオプションがあります。 DayanはObject.assignについて言及していますが、オブジェクトの構造化やES6機能も使用できます。中

const otherStyles = { 
    height: '20px', 
    backgroundColor: 'blue' 
} 

const inlineStyle = { 
    width: '10%' 
} 

const deconstructed = {...otherStyles, ...inlineStyle} 
const assign = Object.assign(otherStyles, inlineStyle) 

両方の結果:

class Example extends React.Component { 
    render() { 

    const otherStyles = { 
     height: '20px', 
     backgroundColor: 'blue' 
    } 

    return (
     {this.props.items.map((d, i) => { 
     return (
      // also include otherStyles with destructuring 
      <div style={{width: i * 10 + '%', ...otherStyles}}></div> 
     ) 
     }} 
     {this.props.items.map((d, i) => { 
     return (
      // also include otherStyles with Object.assign 
      <div style={Object.assign(otherStyles, {width: i * 10 + '%'}}></div> 
     ) 
     }} 
    ) 
    } 
} 
関連する問題