React组件中的this

构造函数内绑定 this

在构造函数 constructor 内绑定this,好处是仅需要绑定一次,避免每次渲染时都要重新绑定,函数在别处复用时也无需再次绑定

通过 bind 方法或者箭头函数来强制绑定 this

render函数中的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

结果如图:

可以看到,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():

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

由此可以看出:

  1. render中this -> 组件实例App对象;
  2. render中this.handler() -> 组件实例App对象 ;
  3. render中window.handler() -> window对象;
  4. onClick ={this.handler} -> undefined
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);
}

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

<!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}“单击”按钮,“更新”和“卸载”按钮结果如下:

render() 以及 componentDIdMount()、componentDIdUpdate() 等其他生命周期函数中的this都是组件实例;
 this.handler()的调用者,为render()中的this,所以打印组件实例;
 window.handler()的“调用者”,为window,所以打印window;
 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到组将实例。

React内部使用了自己的合成事件,如果是使用React.createClass创建的组件内部函数this会绑定该组件,所以this为该组件;但是对于使用class创建的不会自动绑定,所以需要手动绑定,onClick={this.handler}这里只是为click事件指定回调函数,因为在render函数中这里this指向组件这里就相当与onClick={App.handler}的形式,只有在单击事件触发时handler才会执行,但这时已经没发明确是谁调用的handler了(所以此时它内部的this具不确定所以为undefined,如果这时内部使用this.state就会报错),所以当我们需要在handler运行时保持明确的this指向,就需要在将其在明确的环境里进行手动绑定;需要明确的是我们对组件内函数进行this绑定是为了在函数内调用组件实例中的属性或方法(如获取状态this.state等);如果函数内部完全不需要获取组件实例,那可以没有必要进行绑定

猜你喜欢

转载自blog.csdn.net/zlzbt/article/details/89642460