有条件地应用单一属性做出反应?

时间:2016-12-27 00:48:26

标签: reactjs

是否有更短/内联版本的反应,基本上有条件地应用单个css属性?

  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 个答案:

答案 0 :(得分: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' }
  }}
/>