2016-12-27 5 views
0

基本的に単一のcss属性を条件付きで適用すると、反応の中でより短い/インラインバージョンがありますか?この文脈でreactに条件付きで単一の属性を適用しますか?

setStyle() { 
    const style = { 
     display: 'flex', 
     flexDirection: 'column', 
     height: 485 
    } 
    if (this.state.zoom) { 
     style.position = 'absolute' 
    } 
    return style 
    } 

    <div ref='container' style={this.setStyle()}> 

何か:

style={{ 
    display: 'flex', 
    flexDirection: 'column', 
    height: 485 
    position: absolute // Make this conditional 
}} 

答えて

1

Object.assign

let style = Object.assign({ 
    display: 'flex' 
}, this.state.zoom && { position: 'absolute' }) 

使用spread/rest properties

let style = { 
    display: 'flex', 
    ...this.state.zoom && { position: 'absolute' } 
} 

インラインを使用して、インライン:

<div 
    style={ 
    Object.assign({ 
     display: 'flex' 
    }, this.state.zoom && { position: 'absolute' }) 
    } 
/> 

<div 
    style={{ 
    display: 'flex', 
    ...this.state.zoom && { position: 'absolute' } 
    }} 
/> 
+0

レンダリングの質問を更新する際にスタイル属性をそのまま使用できると思っていました。 – Himmators

+0

はい、まったく同じです。 – azium

+0

私は今、愚かな気分です! – Himmators

関連する問題