在React组件中详细讲解this的使用方法。

这篇文章主要介绍了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(      

        

hello World

                              )  }}export default App

登录后复制

结果如图:

在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

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

        

hello World

                              )  }}export default App

登录后复制

在React组件中详细讲解this的使用方法。

可以看到:

render中this -> 组件实例App对象;

render中this.handler() -> 组件实例App对象 ;

render中window.handler() -> window对象;

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(,root);window.renderComponent = () => {  console.log("挂载");  instance = render(,root);}window.setState = () => {  console.log("更新");  instance.setState({foo: 'bar'});}window.unmountComponentAtNode = () => {  console.log('卸载');  unmountComponentAtNode(root);}

登录后复制

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

/index.html

nbsp;html>  react-this        

      

登录后复制

运行程序,依次单击“挂载”,绑定onClick={this.handler}“单击”按钮,“更新”和“卸载”按钮结果如下:

在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(      

        

hello World

                              )  }}export default App

登录后复制

将this.handler()绑定为组件实例后,this.handler()中的this就指向组将实例,即onClick={this.handler}打印出来的为组件实例;

总结:

React组件生命周期函数中的this指向组件实例;

自定义组件方法的this会因调用者不同而不同;

为了在组件的自定义方法中获取组件实例,需要手动绑定this到组将实例。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

vue获取当前激活路由的方法

vue中实现先请求数据再渲染dom分享

解决vue页面DOM操作不生效的问题

以上就是在React组件中详细讲解this的使用方法。的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2750383.html

(0)
上一篇 2025年3月8日 05:35:19
下一篇 2025年3月4日 21:38:37

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论