在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);

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


当前回答

对于那些在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/

其他回答

与React Native不同,我们不能在React中传递样式数组,比如

<View style={[style1, style2]} />

在React中,我们需要在将其传递给style属性之前创建单个样式对象。如:

const Header = (props) => {
  let baseStyle = {
    color: 'red',
  }

  let enhancedStyle = {
    fontSize: '38px'
  }

  return(
    <h1 style={{...baseStyle, ...enhancedStyle}}>{props.title}</h1>
  );
}

我们使用ES6 Spread运算符来组合两种风格。你也可以使用Object.assign()来达到同样的目的。

如果你不需要将你的样式存储在一个变量中,这也可以工作

<Segment style={{...segmentStyle, ...{height:'100%'}}}>
    Your content
</Segment>

数组表示法是react native中组合样式的最佳方式。

这展示了如何组合2个Style对象,

<Text style={[styles.base, styles.background]} >Test </Text>

这展示了如何组合样式对象和属性,

<Text style={[styles.base, {color: 'red'}]} >Test </Text>

这将适用于任何react本机应用程序。

内联样式化的方法:

<View style={[styles.red, {fontSize: 25}]}>
  <Text>Hello World</Text>
</View>

<View style={[styles.red, styles.blue]}>
  <Text>Hello World</Text>
</View>

  <View style={{fontSize:10,marginTop:10}}>
  <Text>Hello World</Text>
</View>

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

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

如果你正在使用React Native,你可以使用数组符号:

<View style={[styles.base, styles.background]} />

请查看我关于这方面的详细博文。