[React] Intro to inline styles in React components

≡放荡痞女 提交于 2020-02-27 15:29:22

React lets you use "inline styles" to style your components; inline styles in React are just JavaScript objects that you can render in an element's style attribute. The properties of these style objects are just like the CSS property, but they are camel case (borderRadius) instead of kebab-case (border-radius). React inline styles allow you to use all the JavaScript you know and love like variables, loops, ES6 modules etc. with your styles. React then renders these properties as inline styles in the output HTML, which means that styles are scoped to the component itself - no more cascading issues or trying to figure out how to re-use a component...everything that belongs to a component is self contained with the component!

 

/*main.js*/
import React from 'react';
import Example from './example';

React.render(<Example content="Button"/>, document.body);

 

/*example.js*/

import React, {Component} from 'react';
import styles from './styles/styles';

class Example extends Component {
    render() {
        return (
            <p style={styles}>{this.props.content} Hello</p>
        );
    }
}

Example.propTypes = {
    content: React.PropTypes.string.isRequired
};

export default Example;

 

styles.js

const baseColor = '#4D54D8';
const borderColor = "#080E73";
const fontColor = "white";

var styles = {
    color: `${fontColor}`,
    background: `${baseColor}`,
    borderRadius: '1rem',
    border: `1px solid ${borderColor}`,
    width: '150px',
    height: '30px',
    fontSize: '1rem',
    textAlign: 'center'
};

export default styles;

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!