How to combine multiple inline style objects?

后端 未结 17 1437
难免孤独
难免孤独 2020-11-28 18:54

In React you can clearly create an object and assign it as an inline style. i.e.. mentioned below.

var divStyle = {
          


        
相关标签:
17条回答
  • 2020-11-28 19:32

    Unlike React Native, we cannot pass array of styles in React, like

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

    In React, we need to create the single object of styles before passing it to style property. Like:

    const Header = (props) => {
      let baseStyle = {
        color: 'red',
      }
    
      let enhancedStyle = {
        fontSize: '38px'
      }
    
      return(
        <h1 style={{...baseStyle, ...enhancedStyle}}>{props.title}</h1>
      );
    }
    

    We have used ES6 Spread operator to combine two styles. You can also use Object.assign() as well for the same purpose.

    This also works if you don't need to store your style in a var

    <Segment style={{...segmentStyle, ...{height:'100%'}}}>
        Your content
    </Segment>
    
    0 讨论(0)
  • 2020-11-28 19:32

    I've found that this works best for me. It overrides as expected.

    return <View style={{...styles.local, ...styles.fromProps}} />
    
    0 讨论(0)
  • 2020-11-28 19:39

    If you're using React Native, you can use the array notation:

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

    Check out my detailed blog post about this.

    0 讨论(0)
  • 2020-11-28 19:39

    You can use the spread operator:

     <button style={{...styles.panel.button,...styles.panel.backButton}}>Back</button
    
    0 讨论(0)
  • 2020-11-28 19:40
        const style1 = {
            backgroundColor: "#2196F3", 
        }
        
        const style2 = {
            color: "white", 
        }
    
        const someComponent = () => {
            return <div style={{ ...style1, ...style2 }}>This has 2 separate styles</div> 
        }
        
    

    Note the double curly brackets. The spread operator is your friend.

    0 讨论(0)
  • 2020-11-28 19:43

    Ways of inline styling:

    <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>
    
    0 讨论(0)
提交回复
热议问题