Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xgqfrms-GitHub/a36b56ac3c0b4a7fe948f2defccf95ea to your computer and use it in GitHub Desktop.
Save xgqfrms-GitHub/a36b56ac3c0b4a7fe948f2defccf95ea to your computer and use it in GitHub Desktop.
class components props & function components (props)

Raect Components props in deepth

https://facebook.github.io/react/docs/react-component.html#setstate

Class Component this.props.onClickFunction !== Function Component props.onClickFunction

this.props 是自己的特有属性,props 除了包含自己所有的属性,还包含从父级组件继承的属性

class components props & this.props.onClickFunction

function components (props) & no need this

// https://facebook.github.io/react/docs/react-component.html#setstate


// class props & this.props.onClickFunction

class PropsTest extends React.Component{
    render() {
        return (
            <div>
                <button onClick={this.props.onClickFunction} >
                    Add counter
                </button>
                <p>
                    this state is 
                    <span 
                        style={{color: "#0ff", fontSize: "32px"}}
                        >
                        {this.props.counter}
                    </span>
                </p>
            </div>
        );
    };
};

// function props & no need this

const Test = (props) =>{
    return (
        <div>
            <button onClick={props.onClickFunction} >
                Add `props` counter
            </button>
            <p
                style={{color: "#0ff", fontSize: "32px"}}
                >
                {props.counter}
            </p>
        </div>
    );
};



class App extends React.Component{
    state = {
        counter: 1
    };
    addCounter = () => {
        this.setState(
          (prevState) => (
              {
                  counter: prevState.counter + 1
              }
          )
        );
    };
    render(){
        return(
            <div>
                <PropsTest 
                    onClickFunction={this.addCounter}
                    counter={this.state.counter}
                    />
                <Test 
                    onClickFunction={this.addCounter}
                    counter={this.state.counter}
                    />
            </div>
        );
    }
}


export default App;

const props = {
    name: "xgqfrms",
    age: 17
};

ReactDOM.render(
    <div>
        <App {...props}/>
    </div>
    , mountNode
);
@xgqfrms-GitHub
Copy link
Author

xgqfrms-GitHub commented Jun 29, 2017

React 父子组件之间 通信

子组件(props)使用props.counter 访问state

父组件 class 中间使用 this.state.counter 访问state

{this.props.counter}

{props.counter}

@xgqfrms-GitHub
Copy link
Author

github api

https://api.github.com

https://developer.github.com/v3/

https://developer.github.com/v4/

{
    "current_user_url": "https://api.github.com/user",
    "current_user_authorizations_html_url": "https://github.com/settings/connections/applications{/client_id}",
    "authorizations_url": "https://api.github.com/authorizations",
    "code_search_url": "https://api.github.com/search/code?q={query}{&page,per_page,sort,order}",
    "commit_search_url": "https://api.github.com/search/commits?q={query}{&page,per_page,sort,order}",
    "emails_url": "https://api.github.com/user/emails",
    "emojis_url": "https://api.github.com/emojis",
    "events_url": "https://api.github.com/events",
    "feeds_url": "https://api.github.com/feeds",
    "followers_url": "https://api.github.com/user/followers",
    "following_url": "https://api.github.com/user/following{/target}",
    "gists_url": "https://api.github.com/gists{/gist_id}",
    "hub_url": "https://api.github.com/hub",
    "issue_search_url": "https://api.github.com/search/issues?q={query}{&page,per_page,sort,order}",
    "issues_url": "https://api.github.com/issues",
    "keys_url": "https://api.github.com/user/keys",
    "notifications_url": "https://api.github.com/notifications",
    "organization_repositories_url": "https://api.github.com/orgs/{org}/repos{?type,page,per_page,sort}",
    "organization_url": "https://api.github.com/orgs/{org}",
    "public_gists_url": "https://api.github.com/gists/public",
    "rate_limit_url": "https://api.github.com/rate_limit",
    "repository_url": "https://api.github.com/repos/{owner}/{repo}",
    "repository_search_url": "https://api.github.com/search/repositories?q={query}{&page,per_page,sort,order}",
    "current_user_repositories_url": "https://api.github.com/user/repos{?type,page,per_page,sort}",
    "starred_url": "https://api.github.com/user/starred{/owner}{/repo}",
    "starred_gists_url": "https://api.github.com/gists/starred",
    "team_url": "https://api.github.com/teams",
    "user_url": "https://api.github.com/users/{user}",
    "user_organizations_url": "https://api.github.com/user/orgs",
    "user_repositories_url": "https://api.github.com/users/{user}/repos{?type,page,per_page,sort}",
    "user_search_url": "https://api.github.com/search/users?q={query}{&page,per_page,sort,order}"
}

@xgqfrms-GitHub
Copy link
Author

xgqfrms-GitHub commented Jun 29, 2017

https://api.github.com/users/xgqfrms

{
    "login": "xgqfrms",
    "id": 7291672,
    "avatar_url": "https://avatars1.githubusercontent.com/u/7291672?v=3",
    "gravatar_id": "",
    "url": "https://api.github.com/users/xgqfrms",
    "html_url": "https://github.com/xgqfrms",
    "followers_url": "https://api.github.com/users/xgqfrms/followers",
    "following_url": "https://api.github.com/users/xgqfrms/following{/other_user}",
    "gists_url": "https://api.github.com/users/xgqfrms/gists{/gist_id}",
    "starred_url": "https://api.github.com/users/xgqfrms/starred{/owner}{/repo}",
    "subscriptions_url": "https://api.github.com/users/xgqfrms/subscriptions",
    "organizations_url": "https://api.github.com/users/xgqfrms/orgs",
    "repos_url": "https://api.github.com/users/xgqfrms/repos",
    "events_url": "https://api.github.com/users/xgqfrms/events{/privacy}",
    "received_events_url": "https://api.github.com/users/xgqfrms/received_events",
    "type": "User",
    "site_admin": false,
    "name": "xgqfrms",
    "company": "xray",
    "blog": "https://www.xgqfrms.xyz",
    "location": "shanghai",
    "email": null,
    "hireable": true,
    "bio": "Hello World!",
    "public_repos": 202,
    "public_gists": 3,
    "followers": 28,
    "following": 1,
    "created_at": "2014-04-14T15:12:30Z",
    "updated_at": "2017-06-10T09:04:07Z"
}

@xgqfrms-GitHub
Copy link
Author

xgqfrms-GitHub commented Jun 29, 2017

CardList

const styles = {
    width: "100px",
    height: "100px",
    border: "3px solid red"
};

const Card = (props) =>{
    return (
        <div>
            <button>username: {props.name}</button>
            <img src={props.avatar} style={styles}/>
            <p
                style={{color: "#0ff", fontSize: "23px"}}
                >
                {props.avatar}
            </p>
            <div>company : {props.company}</div>
        </div>
    );
};


const CardList = (props) =>{
    return (
        <div>
            {
                props.cards.map(
                    (card) => {
                        return (<Card {...card}/>);
                    }
                )
            }
        </div>
    );
};

// ??? fetch datas & loop array/object
// 
const datas = [
    {
        name: "xgqfrms",
        avatar: "https://avatars1.githubusercontent.com/u/7291672?v=3",
        company: "xray"
    },
    {
        name: "xgqfrms007",
        avatar: "https://avatars1.githubusercontent.com/u/7291672?v=3",
        company: "ddinfo"
    },    {
        name: "xgqfrms2007",
        avatar: "https://avatars1.githubusercontent.com/u/7291672?v=3",
        company: "gildata"
    }
];


ReactDOM.render(
    <div>
        <CardList cards={datas}/>
    </div>
    , mountNode
);

export default CardList;

@xgqfrms-GitHub
Copy link
Author

@xgqfrms-GitHub
Copy link
Author

Context

https://facebook.github.io/react/docs/context.html

// contextTypes = {}


// getChildContext(){}

// childContextTypes = {}


constructor(props, context);

componentWillReceiveProps(nextProps, nextContext);

shouldComponentUpdate(nextProps, nextState, nextContext);

componentWillUpdate(nextProps, nextState, nextContext);

componentDidUpdate(prevProps, prevState, prevContext);

@xgqfrms-GitHub
Copy link
Author

Raect Components props in deepth

https://facebook.github.io/react/docs/react-component.html#setstate

Class Component this.props.onClickFunction !== Function Component props.onClickFunction

this.props 是自己的特有属性,props 除了包含自己所有的属性,还包含从父级组件继承的属性

@xgqfrms-GitHub
Copy link
Author

xgqfrms-GitHub commented Jun 30, 2017

OK

Test 组件包含从父级组件继承的属性 props ,所以 OK

// function props & no need this

const Test = (props) =>{
    return (
        <div>
            <button onClick={props.onClickFunction} >
                Add `props` counter
            </button>
            <p
                style={{color: "#0ff", fontSize: "32px"}}
                >
                {props.counter}
            </p>
        </div>
    );
};

error

TypeError: Cannot read property 'onClickFunction' of undefined

Test 组件不具有自己的特有属性,所以是 undefined 属性

const Test = (props) =>{
    return (
        <div>
            <button onClick={this.props.onClickFunction} >
                Add `props` counter
            </button>
            <p
                style={{color: "#0ff", fontSize: "32px"}}
                >
                {props.counter}
            </p>
        </div>
    );
};

@xgqfrms-GitHub
Copy link
Author

OK

// class props & this.props.onClickFunction

class PropsTest extends React.Component{
    render() {
        return (
            <div>
                <button onClick={this.props.onClickFunction} >
                    Add counter
                </button>
                <p>
                    this state is 
                    <span 
                        style={{color: "#0ff", fontSize: "32px"}}
                        >
                        {this.props.counter}
                    </span>
                </p>
            </div>
        );
    };
};

Error

spuer(props)

    constructor(props) {
        super(props);
        this.state = {
            theme: 'dark',
            current: '1',
            message: props.message,
            styles: props.styles,
            Any: props.any,
            width: props.width,
            routes: routes,
            ClickHandler: props.ClickHandler
        };
        this.handleClick = this.handleClick.bind(this);
    }
// class props & this.props.onClickFunction

class PropsTest extends React.Component{
    render() {
        return (
            <div>
                <button onClick={props.onClickFunction} >
                    Add counter
                </button>
                <p>
                    this state is 
                    <span 
                        style={{color: "#0ff", fontSize: "32px"}}
                        >
                        {this.props.counter}
                    </span>
                </p>
            </div>
        );
    };
};

@xgqfrms-GitHub
Copy link
Author

add-multiple-event-handlers-to-same-event-in-react

https://stackoverflow.com/questions/33398613/how-to-add-multiple-event-handlers-to-same-event-in-react-js

<div style={{ display: 'flex' }}>
    <div style={{
            width: '270px',
            background: '#f0f0f0',
            borderRight: "30px solid red",
            minHeight: ' 500px',
            maxHeight: '700px',
            overflowX: 'hidden',
            overflowY: 'scroll',
        }}
        onClick={this.state.ClickHandler}
        onClick={this.stateHandleClick}
        className="sidebar-btn"
        >
        <button onClick={this.props.ClickHandler}>props</button>
        <button onClick={(e) => this.props.ClickHandler}>props</button>
        <button onClick={this.props.ClickHandler}>props</button>
        <button onClick={this.state.ClickHandler}>state</button>
 //...
</div>

@xgqfrms-GitHub
Copy link
Author

(e) => this.handleClick(e)

<button onClick={(e) => this.handleClick(e)}>

https://facebook.github.io/react/docs/handling-events.html

class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }

  render() {
    // This syntax ensures `this` is bound within handleClick
    return (
      <button onClick={(e) => this.handleClick(e)}>
        Click me
      </button>
    );
  }
}

@xgqfrms-GitHub
Copy link
Author

@xgqfrms-GitHub
Copy link
Author

import React, { Component } from 'react';
import PropTypes from 'prop-types';

import logo from './logo.svg';
import './App.css';

import SideBox from './SideBox.js';

import ContentBox from './ContentBox.js';

// import TestRouters from './TestRouters.js';


/*import SidebarExample from './test.js';*/

import {
    BrowserRouter as Router,
    Route,
    Link
} from 'react-router-dom';

import Item1 from './components/Item1.js';
import Item2 from './components/Item2.js';
import Item3 from './components/Item3.js';


const routes = [
    {
        path: '/',
        exact: true,
        sidebar: () => <div>item1</div>,
        main: () => <div><Item1 /></div>
    },
    {
        path: '/item2',
        sidebar: () => <div>item2</div>,
        main: () => <div><Item2 /></div>
    },
    {
        path: '/item3',
        sidebar: () => <div>item3</div>,
        main: () => <div><Item3 /></div>
    }
]

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            message: props.message,
            styles: props.styles,
            Any: props.any,
            width: props.width,
            routes: routes
        };
        // this.handlerMenuClick = this.handlerMenuClick.bind(this);
    }
    handlerMenuClick(e) {
        console.log("clicked === \n", e);
        if(this.state.styles === "App-SideBox-init"){
            this.setState({
                message: "e.key",
                styles: "App-SideBox-New",
                width: "width: 40px;"
            });
        }
        if(this.state.styles === "App-SideBox-New"){
            this.setState({
                message: "Hello!",
                styles: "App-SideBox-init",
                width: "width: 300px;"
            });
        }
        console.log("this.state.message === ", this.state.message);
        console.log("this.state.styles === ", this.state.styles);
    }
    render() {
        return (
            <div className="App">
                <div className="App-header">
                    <img src={logo} className="App-logo" alt="logo" style={this.props.width}/>
                    <h2>React 微盘交易管理系统</h2>
                </div>
                <div className="App-body">
                    <ContentBox routes={routes} ClickHandler={(e)=> this.handlerMenuClick(e)} styles={this.state.styles}/>
                </div>
            </div>
        );
    }
};

App.defaultProps = {
    message: 'Hello!',
    styles: 'App-SideBox-init'
};

App.propTypes = {
    message: PropTypes.string.isRequired,
    styles: PropTypes.string.isRequired,
    width: PropTypes.string
};

export default App;

APP

@xgqfrms-GitHub
Copy link
Author

(e) => this.handleClick(e)

import React, {Component} from 'react';

import {
    BrowserRouter as Router,
    Route,
    Link
} from 'react-router-dom';

import Item1 from './components/Item1.js';
import Item2 from './components/Item2.js';
import Item3 from './components/Item3.js';



import './contentbox.css';

import {Layout, Menu, Icon} from 'antd';
import 'antd/dist/antd.css';

const {Header, Content, Footer, Sider} = Layout;
const SubMenu = Menu.SubMenu;


const routes = [
    {
        path: '/',
        exact: true,
        sidebar: () => <div>item1</div>,
        main: () => <div><Item1 /></div>
    },
    {
        path: '/item2',
        sidebar: () => <div>item2</div>,
        main: () => <div><Item2 /></div>
    },
    {
        path: '/item3',
        sidebar: () => <div>item3</div>,
        main: () => <div><Item3 /></div>
    }
];



class ContentBox extends Component {
    constructor(props) {
        super(props);
        this.state = {
            theme: 'dark',
            current: '1',
            message: props.message,
            styles: props.styles,
            Any: props.any,
            width: props.width,
            routes: routes,
            ClickHandler: props.ClickHandler
        };
        this.handleClick = this.handleClick.bind(this);
        this.stateHandleClick = this.stateHandleClick.bind(this);
    }
    handleClick(e) {
        // e.preventDefault();
        // e.stopPropagation();
        // e.nativeEvent.stopImmediatePropagation();
        console.log('click ', e);
        this.setState({
            current: e.key,
        });
    }
    addClick = (prevState, props) => {
        this.setState({
            // prevState, props
        });
    }
    stateHandleClick(e) {
        // (prevState, props)
        console.log('click ', e);
        this.setState({
            current: e.key,
        });
    }
    render() {
        // let routes = [this.props.routes];
        return (
            <Router>
                <div style={{display: 'flex'}} className={this.props.styles}>
                    <div style={{
                            width: '270px',
                            background: '#f0f0f0',
                            borderRight: "30px solid red",
                            minHeight: ' 500px',
                            maxHeight: '700px',
                            overflowX: 'hidden',
                            overflowY: 'scroll',
                        }}
                        className="sidebar-btn"
                        >
                        <button onClick={this.props.ClickHandler}>props</button>
                        <button onClick={(e) => this.props.ClickHandler(e)}>props</button>
                        {/**/}
                        <button onClick={this.state.ClickHandler}>state</button>
                        <button onClick={(e) => this.state.ClickHandler(e)}>state</button>
                        <Menu
                                theme={this.state.theme}
                                onClick={this.handleClick}
                                style={{ width: 240 }}
                                defaultOpenKeys={['sub1']}
                                selectedKeys={[this.state.current]}
                                mode="inline"
                            >
                            <SubMenu 
                                    key="sub1"
                                    title={
                                        <span>
                                            <Icon type="area-chart" style={{fontSize: 18, color: '#0f0'}} className=""/>
                                            <span style={{fontSize: 16, color: 'rgba(255, 255, 255, 0.7)'}} className="">用户管理</span>
                                        </span>
                                    }
                                >
                                <Menu.Item key="1">
                                    <Link to="/">
                                        <Icon type="area-chart" style={{fontSize: 12, color: '#ff0'}}/>
                                        用户查询
                                    </Link>
                                </Menu.Item>
                                <Menu.Item key="2">
                                    <Link to="/item2">
                                        <Icon type="area-chart" style={{fontSize: 12, color: '#ff0'}}/>
                                        登录统计
                                    </Link>
                                </Menu.Item>
                                <Menu.Item key="3">
                                    <Link to="/item3">
                                        <Icon type="area-chart" style={{fontSize: 12, color: '#ff0'}}/>
                                        行为分析
                                    </Link>
                                </Menu.Item>
                            </SubMenu>
                            <SubMenu 
                                    key="sub2" 
                                    title={
                                        <span>
                                            <Icon type="setting" style={{fontSize: 18, color: '#fff'}}/>
                                            <span>权限管理</span>
                                        </span>
                                    }
                                >
                                <Menu.Item key="4">
                                    <Link to="/item3">
                                        <Icon type="setting" style={{fontSize: 12, color: '#f0f'}}/>
                                        角色管理
                                    </Link>
                                </Menu.Item>
                                <Menu.Item key="5">
                                    <Link to="/item3">
                                        <Icon type="setting" style={{fontSize: 12, color: '#f0f'}}/>
                                        绑定设置</Link>
                                </Menu.Item>
                                <Menu.Item key="6">
                                    <Link to="/item3">
                                        <Icon type="setting" style={{fontSize: 12, color: '#f0f'}}/>
                                        限制设置
                                    </Link>
                                </Menu.Item>
                                <Menu.Item key="7">
                                    <Link to="/item3">
                                        <Icon type="setting" style={{fontSize: 12, color: '#f0f'}}/>
                                        用户权限设置
                                    </Link>
                                </Menu.Item>
                                <Menu.Item key="8">
                                    <Link to="/item3">
                                        <Icon type="setting" style={{fontSize: 12, color: '#f0f'}}/>
                                        用户限制
                                    </Link>
                                </Menu.Item>
                                <Menu.Item key="9">
                                    <Link to="/item3">
                                        <Icon type="setting" style={{fontSize: 12, color: '#f0f'}}/>
                                        角色权限设置
                                    </Link>
                                </Menu.Item>
                            </SubMenu>
                            <SubMenu 
                                    key="sub3" 
                                    title={
                                        <span>
                                            <Icon type="idcard" style={{fontSize: 18, color: '#0f0'}}/>
                                            <span>信息管理</span>
                                        </span>
                                    }
                                >
                                <Menu.Item key="10">
                                    <Link to="/item3">
                                        <Icon type="idcard" style={{fontSize: 12, color: '#fff'}}/>
                                        产品管理
                                    </Link>
                                </Menu.Item>
                                <Menu.Item key="11">
                                    <Link to="/item3">
                                        <Icon type="idcard" style={{fontSize: 12, color: '#fff'}}/>
                                        模块管理
                                    </Link>
                                </Menu.Item>
                                <Menu.Item key="12">
                                    <Link to="/item3">
                                        <Icon type="idcard" style={{fontSize: 12, color: '#fff'}}/>
                                        类库管理
                                    </Link>
                                </Menu.Item>
                                <Menu.Item key="13">
                                    <Link to="/item3">
                                        <Icon type="idcard" style={{fontSize: 12, color: '#fff'}}/>
                                        功能管理
                                    </Link>
                                </Menu.Item>
                                <Menu.Item key="14">
                                    <Link to="/item3">
                                        <Icon type="idcard" style={{fontSize: 12, color: '#fff'}}/>
                                        资源管理
                                    </Link>
                                </Menu.Item>
                                <Menu.Item key="15">
                                    <Link to="/item3">
                                    <Icon type="idcard" style={{fontSize: 12, color: '#fff'}}/>
                                    菜单管理</Link>
                                </Menu.Item>
                            </SubMenu>
                        </Menu>
                    </div>
                    <div style={{ flex: 1, padding: '10px', overflow: 'auto'}}>
                        {routes.map((route, index) => (
                            <Route
                                key={index}
                                path={route.path}
                                exact={route.exact}
                                component={route.main}
                            />
                        ))}
                    </div>
                </div>
            </Router>
        );
    }
};

export default ContentBox;


@xgqfrms-GitHub
Copy link
Author

<button onClick={this.props.ClickHandler}>props</button>
<button onClick={(e) => this.props.ClickHandler(e)}>props</button>
{/**/}
<button onClick={this.state.ClickHandler}>state</button>
<button onClick={(e) => this.state.ClickHandler(e)}>state</button>

@xgqfrms-GitHub
Copy link
Author

import React, {Component} from 'react';

import {UserQuery} from './UserQuery';
import {LoginStatistics} from './LoginStatistics';
import {BehaviorAnalysis} from './BehaviorAnalysis';

import {RoleManagement} from './RoleManagement';
import {BindingSettings} from './BindingSettings';
import {LimitSettings} from './LimitSettings';
import {UserRightsSettings} from './UserRightsSettings';
import {UserRestrictions} from './UserRestrictions';
import {RolePermissionSettings} from './RolePermissionSettings';

import {ProductManagement} from './ProductManagement';
import {ModuleManagement} from './ModuleManagement';
import {ClassLibraryManagement} from './ClassLibraryManagement';
import {FunctionalManagement} from './FunctionalManagement';
import {ResourceManagement} from './ResourceManagement';
import {MenuManagement} from './MenuManagement';

class IndexComponents extends Component {
    render() {
        return (
            <div>
                <h1>索引组件 IndexComponents</h1>
                <div>
                    <UserQuery />
                    <LoginStatistics />
                    <BehaviorAnalysis />
                </div>
                <hr/>
                <div>
                    <RoleManagement />
                    <BindingSettings />
                    <LimitSettings />
                    <UserRightsSettings />
                    <UserRestrictions />
                    <RolePermissionSettings />
                </div>
                <hr/>
                <div>
                    <ProductManagement />
                    <ModuleManagement />
                    <ClassLibraryManagement />
                    <FunctionalManagement />
                    <ResourceManagement />
                    <MenuManagement />
                </div>
            </div>
        );
    }
}

export {IndexComponents};
export default IndexComponents;

@xgqfrms-GitHub
Copy link
Author

xgqfrms-GitHub commented Jun 30, 2017

image

ES7 property initializer syntax much better than, an arrow function in the callback

@xgqfrms-GitHub
Copy link
Author

@xgqfrms-GitHub
Copy link
Author

@xgqfrms-GitHub
Copy link
Author

React multi className

    className="sidebar-btn"
    className={this.props.styles}

@xgqfrms-GitHub
Copy link
Author

xgqfrms-GitHub commented Jun 30, 2017

https://gist.github.com/xgqfrms-GitHub/a36b56ac3c0b4a7fe948f2defccf95ea#gistcomment-2136607

<div style={{
        width: '270px',
        background: '#f0f0f0',
        borderRight: "30px solid red",
        minHeight: ' 500px',
        maxHeight: '700px',
        overflowX: 'hidden',
        overflowY: 'scroll',
    }}
    className="sidebar-btn"
    className={this.props.styles}
    >
</div>

@xgqfrms-GitHub
Copy link
Author

xgqfrms-GitHub commented Jun 30, 2017

CSS 优先级 & React sider style

inline style can't be overwrite by .className

CSS 优先级 inline > style > .css

!important > #id > details path > ...

@xgqfrms-GitHub
Copy link
Author

https://developer.mozilla.org/zh-CN/docs/Web/CSS/Specificity

0. 类型选择器(type selectors)(例如, h1)
和 伪元素(pseudo-elements)(例如, ::before)

1. 类选择器(class selectors) (例如,.example),
属性选择器(attributes selectors)(例如, [type="radio"]),
伪类(pseudo-classes)(例如, :hover)

2. ID选择器(例如, #example)

通用选择器(universal selector)(*), 
组合子(combinators) (+, >, ~, ' ')  
和 否定伪类(negation pseudo-class)(:not()) 对特异性没有影响。
(但是,在 :not() 内部声明的选择器是会影响优先级)。

给元素添加的内联样式 (例如, style="font-weight:bold") 总会覆盖外部样式表的任何样式 ,
因此可看作是具有最高的优先级。.

!important 规则例外
当在一个样式声明中使用一个!important 规则时,此声明将覆盖任何其他声明。
虽然技术上很重要与特异性无关,但它与它直接相关。

@xgqfrms-GitHub
Copy link
Author

xgqfrms-GitHub commented Jun 30, 2017

权值

(外部样式)External style sheet <(内部样式)Internal style sheet <(内联样式)Inline style

http://www.cnblogs.com/xugang/archive/2010/09/24/1833760.html

  1. 内联样式表的权值最高 1000;

  2. ID 选择器的权值为 100

  3. Class 类选择器的权值为 10

  4. HTML 标签选择器的权值为 1

CSS 优先级法则:

A 选择器都有一个权值,权值越大越优先;

B 当权值相等时,后出现的样式表设置要优于先出现的样式表设置;

C 创作者的规则高于浏览者:即网页编写者设置的CSS 样式的优先权高于浏览器所设置的样式;

D 继承的CSS 样式不如后来指定的CSS 样式;

E 在同一组属性设置中标有“!important”规则的优先级最大;

@xgqfrms-GitHub
Copy link
Author

http://www.jianshu.com/p/a53ba8e1fe72
http://www.ruanyifeng.com/blog/2009/03/css_selectors.html
https://segmentfault.com/a/1190000005005091
https://segmentfault.com/a/1190000003860309

CSS 优先规则3:优先级关系:

内联样式 > ID 选择器 > 类选择器 = 属性选择器 = 伪类选择器 > 标签选择器 = 伪元素选择器

@xgqfrms-GitHub
Copy link
Author

选择器的权值不能进位

错误的说法

在学习过程中,你可能发现给选择器加权值的说法,即 ID 选择器权值为 100,类选择器权值为 10,标签选择器权值为 1,当一个选择器由多个 ID 选择器、类选择器或标签选择器组成时,则将所有权值相加,然后再比较权值。

这种说法其实是有问题的。

比如一个由 11 个类选择器组成的选择器和一个由 1 个 ID 选择器组成的选择器指向同一个标签,
按理说 110 > 100,应该应用前者的样式,然而事实是应用后者的样式。

错误的原因是:
选择器的权值不能进位。
还是拿刚刚的例子说明,11 个类选择器组成的选择器的总权值为 110,但因为 11 个均为类选择器,
所以其实总权值最多不能超过 100, 你可以理解为 99.99,所以最终应用后者样式。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment