3、React组件中的this

React组件的this是什么

  • 经由历程编写一个简朴组件,并衬着出来,离别打印出自定义函数和render中的this:
import React from 'react';

const STR = '被挪用,this指向:';

class App extends React.Component{
    constructor(){
        super()
    }

    //测试函数
    handler() {
        console.log(`handler ${STR}`,this);
    }

    render(){

        console.log(`render ${STR}`,this);
        return(
            <div>
                <h1>hello World</h1>
                <label htmlFor = 'btn'>单击打印函数handler中this的指向</label>
                <input id = "btn" type="button" value = '单击' onClick = {this.handler}/>
            </div>        
        )
    }
}
export default App

效果如图:
《3、React组件中的this》

  • 能够看到,render函数中的this指向了组件实例,而handler()函数中的this则为undefined,这是为什么?

JavaScript函数中的this

  • 我们都晓得JavaScript函数中的this不是在函数声明的时刻定义的,而是在函数挪用(即运转)的时刻定义的
var student = {
    func: function() {
        console.log(this);
    };
};

student.func();
var studentFunc = student.func;
studentFunc();

这段代码运转,能够看到student.func()打印了student对象,由于此时this指向student对象;而studentFunc()打印了window,由于此时由window挪用的,this指向window。

这段代码抽象的考证了,JavaScript函数中的this不是在函数声明的时刻,而是在函数运转的时刻定义的;

一样,React组件也遵照JavaScript的这类特征,所以组件要领的‘挪用者’差别会致使this的差别(这里的 “挪用者” 指的是函数执行时的当前对象

“挪用者”差别致使this差别

  • 测试:离别在组件自带的性命周期函数以及自定义函数中打印this,并在render()要领中离别运用this.handler(),window.handler(),onCilck={this.handler}这三种要领挪用handler():

/App.jsx

import React from 'react';


const STR = '被挪用,this指向:';

class App extends React.Component{
    constructor(){
        super()
    }

    ComponentDidMount() {
        console.log(`ComponentDidMount ${STR}`,this);
    }

    componentWillReceiveProps() {
        console.log(`componentWillReceiveProps ${STR}`,this);
    }

    shouldComponentUpdate() {
        console.log(`shouldComponentUpdate ${STR}`,this);
        return true;
    }

    componentDidUpdate() {
        console.log(`componentDidUpdate ${STR}`,this);
    }

    componentWillUnmount() {
        console.log(`componentWillUnmount ${STR}`,this);
    }


    //测试函数
    handler() {
        console.log(`handler ${STR}`,this);
    }

    render(){
        console.log(`render ${STR}`,this);

        this.handler();
        window.handler = this.handler;
        window.handler();

        return(

            <div>
                <h1>hello World</h1>
                <label htmlFor = 'btn'>单击打印函数handler中this的指向</label>
                <input id = "btn" type="button" value = '单击' onClick = {this.handler}/>
            </div>        
        )
    }
}
export default App

《3、React组件中的this》

  • 能够看到:

    1. render中this -> 组件实例App对象;
    2. render中this.handler() -> 组件实例App对象 ;
    3. render中window.handler() -> window对象;
    4. onClick ={this.handler} -> undefined
  • 继承运用事宜触发组件的装载、更新和卸载历程:

/index.js

import React from 'react'
import {render,unmountComponentAtNode} from 'react-dom'

import App from './App.jsx'


const root=document.getElementById('root')

console.log("初次挂载");
let instance = render(<App />,root);

window.renderComponent = () => {
    console.log("挂载");
    instance = render(<App />,root);
}

window.setState = () => {
    console.log("更新");
    instance.setState({foo: 'bar'});
}


window.unmountComponentAtNode = () => {
    console.log('卸载');
    unmountComponentAtNode(root);
}

运用三个按钮触发组件的装载、更新和卸载历程:

/index.html

<!DOCTYPE html>
<html>
<head>
    <title>react-this</title>
</head>
<body>
    <button onclick="window.renderComponent()">挂载</button>
    <button onclick="window.setState()">更新</button>
    <button onclick="window.unmountComponentAtNode()">卸载</button>
    <div id="root">
        <!-- app -->
    </div>
</body>
</html>
  • 运转顺序,顺次单击“挂载”,绑定onClick={this.handler}“单击”按钮,“更新”和“卸载”按钮效果以下:

《3、React组件中的this》

1. render()以及componentDIdMount()、componentDIdUpdate()等其他性命周期函数中的this都是组件实例;
2. this.handler()的挪用者,为render()中的this,所以打印组件实例;
3. window.handler()的“挪用者”,为window,所以打印window;
4. onClick={this.handler}的“挪用者”为事宜绑定,泉源多样,这里打印undefined。
- 面临云云杂沓的场景,假如我们想在onClick中挪用自定义的组件要领,并在该要领中猎取组将实例,我们就得举行转换上下文即绑定上下文:

自动绑定和手动绑定

  • React.createClass有一个内置的魔法,能够自动绑定所用的要领,使得其this指向组件的实例化对象,然则其他JavaScript类并没有这类特征;
  • 所以React团队决议不再React组件类中完成自动绑定,把上下文转换的自由权交给开发者;
  • 所以我们通常在组织函数中绑定要领的this指向:
import React from 'react';


const STR = '被挪用,this指向:';

class App extends React.Component{
    constructor(){
        super();

        this.handler = this.handler.bind(this);
    }
//测试函数
    handler() {
        console.log(`handler ${STR}`,this);
    }

    render(){
        console.log(`render ${STR}`,this);

        this.handler();
        window.handler = this.handler;
        window.handler();

        return(

            <div>
                <h1>hello World</h1>
                <label htmlFor = 'btn'>单击打印函数handler中this的指向</label>
                <input id = "btn" type="button" value = '单击' onClick = {this.handler}/>
            </div>        
        )
    }
}
export default App
  • 将this.handler()绑定为组件实例后,this.handler()中的this就指向组将实例,即onClick={this.handler}打印出来的为组件实例;

总结:

  • React组件性命周期函数中的this指向组件实例;
  • 自定义组件要领的this会因挪用者差别而差别;
  • 为了在组件的自定义要领中猎取组件实例,须要手动绑定this到组将实例。
    原文作者:keywords
    原文地址: https://segmentfault.com/a/1190000013425634
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞