在React中,你可以清楚地创建一个对象,并将其赋值为内联样式。即. .下面所提到的。

var divStyle = {
  color: 'white',
  backgroundImage: 'url(' + imgUrl + ')',
  WebkitTransition: 'all', // note the capital 'W' here
  msTransition: 'all' // 'ms' is the only lowercase vendor prefix
};

var divStyle2 = {fontSize: '18px'};

React.render(<div style={divStyle}>Hello World!</div>, mountNode);

如何组合多个对象并将它们分配在一起?


当前回答

为了扩展@PythonIsGreat所说的内容,我创建了一个全局函数来为我做这件事:

var css = function(){
    var args = $.merge([true, {}], Array.prototype.splice.call(arguments, 0));
    return $.extend.apply(null, args);
}

这将对象深度扩展为一个新对象,并允许使用可变数量的对象作为参数。这允许你做这样的事情:

return(
<div style={css(styles.base, styles.first, styles.second,...)} ></div>
);

var styles = {
  base:{
    //whatever
  },
  first:{
    //whatever
  },
  second:{
    //whatever
  }
}

其他回答

我已经为此构建了一个模块,如果你想根据条件添加样式 是这样的:

multipleStyles(styles.icon, { [styles.iconRed]: true })

https://www.npmjs.com/package/react-native-multiple-styles

我发现这个方法最适合我。它会像预期的那样重写。

return <View style={{...styles.local, ...styles.fromProps}} />

要在react js中添加多个内联样式,你可以这样做

<div style={{...styles.cardBody,...{flex:2}}}>

你也可以像这样将类与内联样式结合起来:

<View style={[className, {paddingTop: 25}]}>
  <Text>Some Text</Text>
</View>

对于那些在React中寻找这个解决方案的人,如果你想在风格中使用扩散操作符,你应该使用:babel-plugin-transform-object-rest-spread。

通过npm模块安装它,并配置你的.babelrc:

{
  "presets": ["env", "react"],
  "plugins": ["transform-object-rest-spread"]
}

然后你可以用like…

const sizing = { width: 200, height: 200 }
 <div
   className="dragon-avatar-image-background"
   style={{ backgroundColor: blue, ...sizing }}
  />

更多信息:https://babeljs.io/docs/en/babel-plugin-transform-object-rest-spread/