簡體   English   中英

渲染內聯樣式以及React Component的預定義樣式

[英]Rendering inline styles as well as pre-defined styles for React Component

在React的渲染方法中,如果我循環遍歷數組並渲染結果元素,那么在渲染組件時,如何使用預定義的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回調中的參數的那些樣式。

有沒有辦法在循環內部渲染組件時將其他樣式對象與內聯樣式結合使用?

ES6有兩個不錯的選擇。 正如Dayan提到的Object.assign或者您可以使用對象解構,也可以使用ES6功能。

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

const inlineStyle = {
  width: '10%'
}

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

兩者都導致:

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

更具體地說,我將兩個選項放在下面的渲染方法中:

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>
        )
      }}
    )
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM