react学习(二)

JSX基本语法

元素属性

class 属性改成className;
for属性改成htmlFor;html

Javascript属性表达式

属性值要使用表达式,只要用{}替换""便可。react

HTML转义

React会将全部要显示到DOM的字符串转义,防止XSS。因此,若是JSX中含有转义后的实体字符,好比© 则最后到DOM中不会正确显示,由于React 自动把©中的特殊字符转义了。有几种解决办法:数组

  1. 直接使用UTF-8字符©;函数

  2. 使用对应字符的Unicode编码查询编码;this

  3. 使用数组组装<div>{['cc', <span>©</span>, '2015']}</div>;编码

  4. 直接插入原始的HTMLspa

此外,React提供了dangerouslySetInnerHTML属性。正如其名,它的做用就是避免React转义字符,在肯定必要的状况下能够使用它:code

<div dangerouslySetInnerHTML={{_html: 'cc &copy; 2015'}} />htm

React 与Web Components

React组件的构建方法ip

React.createClass

const Button = React.createClass({
    getDefaultProps() {
        return {
            color: 'blue',
            text: 'confirm'
        };
    },
    
    render() {
        const {color, text} = this.props;
        
        return (
            <button className={'btn btn-${color}'}>
                <em>{text}</em>
            </button>
        );
    }
});

ES6 classes

import React, {Component} from 'react';

class Button extends Component {
    constructor(props) {
        super(props);
    }
    
    static defaultProps = {
        color: 'blue',
        text: 'Confirm'
    }
    
    render() {
        return (
                <button className={'btn btn-${color}'}>
                    <em>{text}</em>
                </button>
         );
    }
}

React 数据流

state 与props 是React组件中最重要的概念。若是顶层组件初始化props, 那么React会向下遍历整棵树,从新尝试渲染全部相关的子组件。而state只关心每一个组件本身内部的状态,这些状态只能在组件内改变。把组件当作一个函数,那么它接受了props做为参数,内部由state做为函数的内部参数,返回一个Virtual DOM实现。

相关文章
相关标签/搜索