React学习笔记2-初识React

这篇七个点:1 环境搭建, 2 JSX, 3 组件,4 数据流,5 生命周期,6 React与DOM,7 实例

1 环境搭建

1.1 引用React CDN

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
<div id="example"></div>
<script type="text/babel">
    ReactDOM.render(
            <h1>bolala</h1>,
        document.getElementById('example')
    )
</script>
</body>
</html>

1.2 利用create-react-app脚手架

npm install -g cnpm --registry=https://registry.npm.taobao.org//使用淘宝镜像
npm config set registry https://registry.npm.taobao.org
set-ExecutionPolicy RemoteSigned //执行本地脚本
A
cnpm install -g create-react-app//安装脚手架
create-react-app my-app //创建文件
cd my-app/
npm start//配置完成

2 JSX

2.1 JSX为什么出现

React中创建虚拟元素分为:DOM元素和组件元素,分别对应原生元素与自定义元素。

  • DOM元素
<button class="btn"><b>bolala</b></button>
<script>
    var btn =
        {
            type: 'button',
            props: {
                className: 'btn', children: {
                    type: 'b',
                    props: {
                        children: "bolala"}
                }
            }
        };
</script>

这样就在JS中创建了DOM的虚拟元素。

  • 组件元素
let Button=({color,test})=>{
        return {
            type: 'button',
            props: {
                className:`btn-${color}`, children: {//模板字符串用反引号
                    type: 'b',
                    props: {
                        children: test}
                }
            }
        };
    };

封装的button元素,这种表达层层嵌套后会很复杂,JSX语法就产生了:

2.2 JSX基础语法

2.2.1 XML语法

<script type="text/babel">
    const Title=()=>(
            <h3>child</h3>
    );
    const List=()=>(
            <div>
                <Title />
                <ul>
                    <li>1</li>
                    <li>2</li>
                    <li>3</li>
                </ul>
            </div>
    );

    ReactDOM.render(
            <List/>,
        document.getElementById('example')
    )
</script>

注意点:

  • 定义标签时,只允许被一个标签包裹!
  • 标签一定要闭合。

2.2.2 元素类型
在JSX中,小写首字母对应DOM元素,组件元素对应大写首字母。
JSX还可以通过命名空间的方式使用组件元素。
要注意的是,在一个组件的子元素位置使用注释要用{}包起来。

2.2.3 元素属性
在JSX中,DOM元素和组件元素都有属性,DOM属性是标准规范属性,class改为className;for改为htmlFor,其他不变。
组件元素的属性是自定义属性,为实现组件所需要的参数。在写自定义属性时,要由标准写法改成小驼峰写法。
属性值要使用表达式,可以 用{}替换"";

3 组件

3.1 组件的演变
3.2 React组件的构建

React组件由三部分组成:属性(props),状态(state)以及生命周期方法。
React组件可以接收参数,也可能有自身状态。一旦接收到的参数或自身状态改变,组件就会执行相应的生命周期方法,最后渲染。

  • 组件的构造方法。
    三种方法:1 React.createClass 最新版本已经放弃
<script type="text/babel">
    var Bolala=React.createClass({
        render:function () {
            return (
                    <h1>{this.props.name}</h1>
            )
        }
    });
    ReactDOM.render(
            <Bolala name="bolala"/>,
        document.getElementById('example')
    )
</script>

2 ES6 classes方法

import React,{Component} from 'react';
import ReactDOM from 'react-dom';

class Button extends Component{
    constructor(props){
        super(props);
    }
    static defaultProps={
        name:"默认"
    };
    render(){
        return (
            <button>{this.props.name}</button>
        )
    }
}

ReactDOM.render(
    <Button name={'bolala'}/>,
    document.getElementById('root')
);
文件结构.png

3 无状态函数

function Bottom(props) {
    const sayHi=()=>{
        console.log(`Hello ${props.name}`);
    };
    return(
      <div>
          <h1>{props.name}</h1>
          <button onClick={sayHi}>显示</button>
      </div>
    )
}

ReactDOM.render(
    <Bottom name={'bolala'}/>,
    document.getElementById('root')
);

无状态组件只传入props和context两个参数,不存在state,也没有生命周期方法,组件本身就是render方法。

4 数据流

state与props是最重要的概念,如果顶层组件初始化props,React会向下遍历整个组件树,重新渲染。state只关心每个组件自己内部的状态。

4.1 state

一般优先使用Redux,它自身也能管理组件的内部状态。
当使用setState方法时,该组件会尝试重新渲染。

class Counter extends Component{
    constructor(props){
        super(props);
        this.state={count:2};
        this.handleClick= this.handleClick.bind(this);
    }
    handleClick(){
        this.setState({
            count:this.state.count+1
        })
    }
    render(){
        return (
            <div>
                <p>{this.state.count}</p>
                <button onClick={this.handleClick}>增加</button>
            </div>
        )
    }
}
ReactDOM.render(
    <Counter/>,
    document.getElementById('root')
);

注意setState是一个异步方法,一个生命周期的所有setState方法会合并操作。

4.2 props

React的单向数据流,主要流动管道就是props,组件的props一定来自于默认属性或通过父组件传递。
React通过defaultProps静态变量的方式来定义。

class SayName extends Component{
    constructor(props){super(props);this.state={};}
    static defaultProps={
        name:"bolala"
    };
    render(){
      return (
          <div>{this.props.name}</div>
      )
    }

}
ReactDOM.render(
    <SayName name="hashiqi"/>,
    document.getElementById('root')
);

React.PropTypes 在 React v15.5 版本后已经移到了 prop-types 库。

<script src="https://cdn.bootcss.com/prop-types/15.6.1/prop-types.js"></script>
class MyTitle extends React.Component {
  render() {
    return (
      <h1>Hello, {this.props.title}</h1>
    );
  }
}
 
MyTitle.propTypes = {
  title: PropTypes.string
};
ReactDOM.render(
    <MyTitle title={title} />,
    document.getElementById('example')
);

5 生命周期

React生命周期分成三类:挂载,更新,卸载

5.1 组件挂载期
class App extends Component{
    constructor(props){
        super(props);this.state={};
        console.log("1 构造函数和state")
    }
    static defaultProps={
        name:"bolala"
    };
    componentWillMount(){
        console.log("2 首次渲染前");

    };
    render(){
        console.log("3 渲染");
        return (
            <div>{this.props.name}</div>
        )
    }
    componentDidMount(){
        console.log("4 render渲染后");
    }
}
ReactDOM.render(
    <App name="hashiqi"/>,
    document.getElementById('root')
);
5.2 组件更新期
class APPFather extends Component{
    constructor(props){
        super(props);this.state={};
        this.update=this.update.bind(this);
    }
    update(){
        this.setState({
            name:"Vue"
        })
    }
    render(){
        return (
            <div>
                <App name1={this.state.name}/>
                <button onClick={this.update}>修改</button>
            </div>
        )
    }
}
class App extends Component{
    constructor(props){
        super(props);this.state={};
        console.log("1 构造函数和state")
    }
    componentWillMount(){
        console.log("2 首次渲染前");

    };
    render(){
        console.log("3 渲染");
        return (
            <div>{this.props.name1?this.props.name1:"bolala"}</div>
        )
    }
    componentDidMount(){
        console.log("4 render渲染后");
    }
    componentWillReceiveProps(){
        console.log("5 父组件更新子组件props时");
    }
    shouldComponentUpdate(){
        console.log("6 props/state改变是否重新渲染");
        return true;
    }
    componentWillUpdate(){
        console.log("7 接受到新props/state,重新渲染前");
    }
    componentDidUpdate(){
        console.log("8 组件被重新渲染后");
    }
    // 执行的顺序是:1,2,3,4,5,6,7,3,8
}
ReactDOM.render(
    <APPFather/>,
    document.getElementById('root')
);
5.3 组件卸载期
componentWillUnmount() {
         console.log('Component WILL UNMOUNT!')
  }
index.png

6 React与DOM

6.1 ReactDOM
  • findDOMNode
    组件的生命周期中,真正被添加DOM中的方法是componentDidMount和componentDidUpdate,ReactDOM。findDOMNode可以获取到真正的DOM元素。
class SayName extends Component{
    constructor(props){super(props);this.state={};}
    static defaultProps={
        name:"bolala"
    };
    componentDidMount(){
        console.log(ReactDOM.findDOMNode(this));
        //返回真实的DOM
    }
    render(){
      return (
          <div>{this.props.name}</div>
      )
    }
}
  • render
    参数1:组件,参数2:DOM元素,参数3:装载完毕执行的回调函数
ReactDOM.render(
    <SayName />,
    document.getElementById('root'),
    function () {
        console.log("加载完毕");
    }
);
6.2 refs

利用render可以得到组件的实例,但是在组件内部JSX并不会反悔一个组件的实例,refs就是为此出现的。refs组件被调用时会新建一个该组件的实例,而refs就会指向这个实例。

class Refs extends Component{
    constructor(props){
        super(props);this.state={};
        this.handle=this.handle.bind(this)
    }
    handle(){
        this.refs.name.focus();
        console.log(this.refs.name);//获得dom元素
    }
    render(){
        return (
            <div>
                <input type="text" ref="name"/>
                <input
                    type="button"
                    value="点击"
                    onClick={this.handle}
                />
            </div>
        )
    }
}

对于DOM操作,不仅可以使用findDOMNode获取该组件DOM,还可以使用refs获取内部的DOM。
要获取一个React组件的引用,即可以使用this来获取当前react组件, 也可以使用refs获取子组件的引用。

class Clild extends Component{
    constructor(props){
        super(props);this.state={};
    }
    render(){
        return(
            <div>
                <h1>标题</h1>
                <h1>bolalalala</h1>
            </div>
        )
    }
}
class Refs extends Component{
    constructor(props){
        super(props);this.state={};
        this.handle=this.handle.bind(this)
    }
    handle(){
        this.refs.name.focus();
        console.log(this.refs.name);//获取input元素
        console.log(this.refs.title);//这个是实例
        console.log(ReactDOM.findDOMNode(this.refs.title));
        //这个是子组件的DOM
        console.log(ReactDOM.findDOMNode(this));
        //这个是整个组件的DOM
    }
    render(){
        return (
            <div>
                <Clild ref="title"/>
                <input type="text" ref="name"/>
                <input
                    type="button"
                    value="点击"
                    onClick={this.handle}
                />
            </div>
        )
    }
}

值得注意的是,findDOMNode和refs都无法用于无状态组建中,无状态组件挂载时只是方法调用,没有新建实例

7 实例

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,458评论 6 513
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,030评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,879评论 0 358
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,278评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,296评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,019评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,633评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,541评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,068评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,181评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,318评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,991评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,670评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,183评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,302评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,655评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,327评论 2 358