React组件三大属性props state refs以及组件的生命周期

props属性

React组件可以通过JavaScript函数方式实现, 那么React组件就可以接受参数的传入。React框架定义了一个Props的概念, 主要用来实现React函数组件接受参数的输入。

props属性:从组件外部向组件内部传递变化了的数据,在组件内部不能改变它的值,props除了可以传字符串、数字,还可以传数组,对象、甚至是回调函数,它的主要作用是从父组件向子组件传递数据,它是不可改变的

读取props属性值: this.props.属性名
向props中传值: <组件名 属性名='值'/>
设置类组件的默认值:组件名.defaultProps={ 属性名:默认值 }

向props中传值

    <div id="example"></div>
    <script type="text/babel">
        // 定义函数组件
        function PropsDemo(props){
            if(props){
                return  (<div>
                        <p>你好:{props.name}</p>
                        <p>年龄:{props.age}</p>
                        </div>)
            }
        }
        // 将函数转化为组件
        const element = <PropsDemo name="梓琳" age="23" gender="Girl"/>
        // 渲染组件
        ReactDOM.render(element,document.getElementById('example'))
    </script>

设置类组件的默认值

    <div id="example"></div>
    <script type="text/babel">
        // 创建类组件
        class PropsComponent extends React.Component{
            render(){
                return (<div>
                            <p>类的默认值:{this.props.default}</p>
                            <p>类的默认值2:{this.props.address}</p>
                        </div>)
            }
        }
        // 定义类组件的默认值
        PropsComponent.defaultProps = {
            default:'西湖',
            address:'杭州'
        }
        const element = <PropsComponent/>
        const reactDiv = (
            <div>{element}</div>
        )
        ReactDOM.render(reactDiv,document.getElementById('example'))
    </script>

state属性

由于React对props有严格的保护机制,一旦给定值,在组件中是不允许改变的,在很多情况下,组件的内容需要根据数据的刷新而刷新,这个时候就可以用到React提供的State,在这里称之为状态机,State与Props都是React的私有的,但不同的是,State是完全受控于组件的,所定义的属性值可以根据需求而改变,并在虚拟DOM上同步更新。

React框架之所以定义这个状态(State) 概念, 目的就是通过更新React组件的状态(State) , 就可以实现重新渲染用户界面的操作(这样就不需要操作DOM了) ,这点也是React设计理念相较于其他前端框架的先进之处,React State的使用方法相比于Props较为复杂一些, 但也是有基本模式的。

特性: 指组件通过与用户交互,实现不同的状态,然后通过渲染UI保证用户界面和数据一致性
应用场景: 组件的内容需要根据数据的刷新而刷新
创建方法: 在类的构造函数中定义

class isState extends React.Component{
			//利用ES6class继承方法可以将props传递到isState构造函数中
            constructor(props){
                super(props);
                // 定义状态机
                this.state = {
                    value:'状态机'
                }
            }
		}

React组件的生命周期(挂载)

生命周期: 组件从创建到加载运行再到卸载的整个过程就是生命周期
注意:只有类组件才有生命周期

每个组件都包含"生命周期方法",可以重写这些方法便于在运行过程中特定的阶段执行这些方法

组件挂载

1.进行组件的构造(初始化): 通过调用constructor函数来实现,为组件定义状态机时必须有构造函数 this.state = {},在给事件绑定函数时必须有构造函数

2.getDerivedStateFromProps(): 获取组件的状态机和props属性值(一般不要重写)

3.进行组件的渲染: render()是class组件(类组件)中必须实现的方法。render()是一个纯函数,需要return返回值,这意味着在不修改组件state的情况下,每次调用时都返回相同的结果,并且它不会直接与浏览器交互。

4.componentDidMount(): 会在组件挂载后(插入 DOM 树中)立即调用

组件更新

当props和state发生改变时,组件就会更新,

1.调用render()方法: 对组件进行重新渲染
2.调用componentDidUpdate()方法: 对挂载的组件进行更新

组件卸载

**调用componentWillUnmount():**会在组件卸载及销毁之前直接调用。在此方法中执行必要的清理操作。例如,清除timer,取消网络请求或清除

挂载(mount):当组件实例被创建并插入 DOM 中时,其生命周期调用顺序如下:
React组件三大属性props state refs以及组件的生命周期_第1张图片
时钟组件的生命周期

<div id="myClock"></div>
    <script type="text/babel">
        class Clock extends React.Component{
            constructor(props){
                super(props);
                this.state = {// 状态机
                    show:true,
                    date:new Date(),
                    text:'隐藏'
                }
                // 在自定义函数中this为null 若要在自定义函数中使用this 就必须进行绑定(将this强制绑定到自定义函数中)
                this.handelShow = this.handelShow.bind(this)
            }
            // 挂载函数(钩子函数)
            componentDidMount(){// 创建定时器 每隔1秒钟调用一次tick函数
                this.timerID = setInterval(()=>{
                    this.tick(),1000
                })
            }
            // 定义tick函数:更新状态机中的date
            tick(){
                this.setState({
                    date:new Date(),
                })
            }
            // 定义事件响应函数 用来更新状态机中的show和text(决定显示在按钮上的文本)
            handelShow(){
                this.setState({
                    show:!this.state.show,
                    text:!this.state.show?'隐藏':'显示'
                })
                // this.setState((state)=>{ //两种写法
                //     show:!state.show;
                //     text:!state.show?'隐藏':'显示'
                // })
            }
            // 组件卸载函数(钩子函数):清除定时器
            componentWillUnmount(){
                clearInterval(this.timerID)
            }
            render(){
                let isShow = this.state.show;
                let element;
                if(isShow){
                    element = <h2>{this.state.date.toLocaleTimeString()}</h2>
                }else{
                    element = null
                }
                return (
                    <div>
                        <button onClick={this.handelShow}>{this.state.text}计时器</button>    
                        <br />
                        {element}
                    </div>
                )
            }
        }
        ReactDOM.render(<Clock/>,document.getElementById('myClock'))
    </script>

React组件三大属性props state refs以及组件的生命周期_第2张图片
点击按钮隐藏时间
React组件三大属性props state refs以及组件的生命周期_第3张图片
props和state区别

  • state:状态机,组件自身的可以变化的数据
  • props:从组件外部向组件传递的数据,在组建内部对props只能读不能改

refs属性

refs属性主要作用是读取组件内部的标签的值,在组件内部可以给标签定义ref属性,用于标识标签,使用 this.refs.标签的ref的属性值 就可以获取对应的标签

在React中获取虚拟组件中的标签的值
1.使用组件的refs属性
2.在虚拟组件的标签中定义事件 在事件中通过箭头函数来获取标签的值
this.input = info)/}
3.使用事件对象—>event

handleBlur(event){ //'event'代表的是产生事件的对象
	alert(event.target.value)
   }
    <div id="text"></div>
    <script type="text/babel">
        // 1.定义组件类
        class RefComponent extends React.Component{
            constructor(props){
                super(props);
                this.showInput = this.showInput.bind(this);
            }
            showInput(){
                const tempInput = this.refs.content;
                alert(tempInput.value);
            }
            handleBlur(event){
                alert(event.target);
            }
            render(){
                return (
                    <div>
                        <input type="text" ref='content' />&nbsp;&nbsp;
                        <button onClick={ this.showInput }>显示</button>                        
                    </div>
                )
            }
        }
        // 2.渲染组件
        ReactDOM.render(<RefComponent/>,document.getElementById('text'))

在这里插入图片描述

你可能感兴趣的:(React,react.js,javascript,react)