首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >呈现内联样式以及React组件的预定义样式。

问呈现内联样式以及React组件的预定义样式。
EN

Stack Overflow用户
提问于 2016-05-04 18:26:34
回答 1查看 49关注 0票数 1

在React的呈现方法中,如果我循环遍历数组并呈现结果元素,那么在呈现组件时,如何使用预定义的style对象以及依赖于map回调中提供的参数的样式?

代码语言:javascript
复制
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回调的参数的样式。

在循环中呈现组件时,是否有方法将附加的样式对象与内联样式结合在一起?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-04 19:05:50

ES6有两个很好的选择。正如Dayan提到的那样,Object.assign或者您可以使用对象析构,这也是一个ES6特性。

代码语言:javascript
复制
const otherStyles = {
  height: '20px',
  backgroundColor: 'blue'
}

const inlineStyle = {
  width: '10%'
}

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

两者的结果都是:

代码语言:javascript
复制
{
  height: '20px',
  backgroundColor: 'blue',
  width: '10%'  
}

更具体地说,我将这两个选项放在下面的render方法中:

代码语言:javascript
复制
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>
        )
      }}
    )
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37035275

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档