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

其他回答

    const style1 = {
        backgroundColor: "#2196F3", 
    }
    
    const style2 = {
        color: "white", 
    }

    const someComponent = () => {
        return <div style={{ ...style1, ...style2 }}>This has 2 separate styles</div> 
    }
    

注意双花括号。播音接线员是你的朋友。

所以基本上我看问题的方式是错误的。从我所看到的,这不是一个React特定的问题,更多的是一个JavaScript问题,在我如何结合两个JavaScript对象在一起(没有打击类似命名的属性)。

在这个StackOverflow的答案中,它解释了这一点。如何动态合并两个JavaScript对象的属性?

在jQuery中,我可以使用extend方法。

其实有一种正式的组合方式,如下所示:

<View style={[style01, style02]} />

但是,有一个小问题,如果其中一个被父组件传递,并且它是通过组合形式的方式创建的,我们就有一个大问题:

// The passing style02 from props: [parentStyle01, parentStyle02]

// Now:
<View style={[style01, [parentStyle01, parentStyle02]]} />

最后一行导致UI bug, React Native不能处理数组中的深数组。所以我创建了我的helper函数:

import { StyleSheet } from 'react-native';

const styleJoiner = (...arg) => StyleSheet.flatten(arg);

通过使用我的styleJoiner,你可以在任何地方组合任何类型的风格和组合风格。即使是未定义的或其他无用的类型也不会破坏样式。

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

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

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

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

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

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

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

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

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