在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回调的参数的样式。
在循环中呈现组件时,是否有方法将附加的样式对象与内联样式结合在一起?
发布于 2016-05-04 19:05:50
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%'
}更具体地说,我将这两个选项放在下面的render方法中:
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>
)
}}
)
}
}https://stackoverflow.com/questions/37035275
复制相似问题