📜  在构造函数中绑定 this 的替代方法是什么?

📅  最后修改于: 2022-05-13 01:56:15.745000             🧑  作者: Mango

在构造函数中绑定 this 的替代方法是什么?

绑定this关键字的概念并没有具体反应,而是特定于 Javascript。我们需要绑定this关键字,因为在简单函数中this关键字的值是未定义的。例如,考虑下面的代码。如果这是功能组件中的单击处理程序,则输出将是未定义的(仅在严格模式下,在非严格模式下它将指向全局对象)。

句法:

function handleClick(event){
   console.log(this); // 'this' is undefined
}

让我们通过例子来理解。

创建 React 应用程序并安装模块:

第 1 步:使用以下命令创建一个 React 应用程序。

npx create-react-app foldername

第 2 步:创建项目文件夹(即文件夹名称)后,使用以下命令移动到该文件夹:

cd foldername

步骤 3:创建 ReactJS 应用程序后,通过以下命令运行开发服务器:

npm start

项目结构:如下所示。

有 3 种替代方法可以在 react 中绑定this关键字。

方法:在下面的所有方法中,我们在 App 组件中创建了一个极客表情符号的状态。单击按钮后,我们会将极客表情符号数组的大小减一。

第一种方法:我们可以在附加事件处理程序的渲染方法中使用箭头函数。这种方法有一个性能影响,即每当组件重新渲染时,都会一次又一次地创建函数。如果 Web 应用程序或组件进行大量重新渲染,这可能会产生性能问题。

句法:

onClick={() => this.handleClick()}
App.js
import "./App.css";
import React, { Component } from "react";
  
export class App extends Component {
  constructor(props) {
    super(props);
    let styles = {
      width: "120px",
      color: "green",
      padding: "5px",
      margin: "2px",
      border: "2px solid green",
    };
    this.state = {
      mustKnowTopics: [
        
          

Searching

        
,         
          

Sorting

        
,         
          

BinarySearch

        
,         
          

SlidingWindow

        
,         
          

Stack's

        
,         
          

Queue's

        
,       ],     };   }      handleClick = () => {     let newTopics = [...this.state.mustKnowTopics];     newTopics = newTopics.slice(0, newTopics.length - 1);     this.setState({       mustKnowTopics: [...newTopics],     });   };      render() {     return (       <>         
          <>             {" "}             

Must know topics

            
              {this.state.mustKnowTopics}             
                              
           );   } }    export default App;


App.js
import "./App.css";
import React, { Component } from "react";
  
export class App extends Component {
  constructor(props) {
    super(props);
    let styles = {
      width: "120px",
      color: "green",
      padding: "5px",
      margin: "2px",
      border: "2px solid green",
    };
    this.state = {
      mustKnowTopics: [
        
          

Searching

        
,         
          

Sorting

        
,         
          

BinarySearch

        
,         
          

SlidingWindow

        
,         
          

Stack's

        
,         
          

Queue's

        
,       ],     };   }      handleClick = () => {     let newTopics = [...this.state.mustKnowTopics];     newTopics = newTopics.slice(0, newTopics.length - 1);     this.setState({       mustKnowTopics: [...newTopics],     });   };      render() {     return (       <>         
           <>             {" "}             

Must know topics

            
              {this.state.mustKnowTopics}             
                              
           );   } }    export default App;


App.js
import "./App.css";
import React, { Component } from "react";
  
export class App extends Component {
  constructor(props) {
    super(props);
    let styles = {
      width: "120px",
      color: "green",
      padding: "5px",
      margin: "2px",
      border: "2px solid green",
    };
    this.state = {
      mustKnowTopics: [
        
          

Searching

        
,         
          

Sorting

        
,         
          

BinarySearch

        
,         
          

SlidingWindow

        
,         
          

Stack's

        
,         
          

Queue's

        
,       ],     };   }      handleClick = () => {     let newTopics = [...this.state.mustKnowTopics];     newTopics = newTopics.slice(0, newTopics.length - 1);     this.setState({       mustKnowTopics: [...newTopics],     });   };      render() {     return (       <>         
          <>             {" "}             

Must know topics

            
              {this.state.mustKnowTopics}             
                              
           );   } }    export default App;


运行应用程序的步骤:打开终端并键入以下命令。

npm start

输出:

方法二:通过bind()在onClick事件处理函数中绑定this关键字。与以前的方法相同,这种方法具有性能影响,因为我们在每次重新渲染时都会不断地重新分配。

句法:

onClick={this.handleClick.bind(this)}

应用程序.js

import "./App.css";
import React, { Component } from "react";
  
export class App extends Component {
  constructor(props) {
    super(props);
    let styles = {
      width: "120px",
      color: "green",
      padding: "5px",
      margin: "2px",
      border: "2px solid green",
    };
    this.state = {
      mustKnowTopics: [
        
          

Searching

        
,         
          

Sorting

        
,         
          

BinarySearch

        
,         
          

SlidingWindow

        
,         
          

Stack's

        
,         
          

Queue's

        
,       ],     };   }      handleClick = () => {     let newTopics = [...this.state.mustKnowTopics];     newTopics = newTopics.slice(0, newTopics.length - 1);     this.setState({       mustKnowTopics: [...newTopics],     });   };      render() {     return (       <>         
           <>             {" "}             

Must know topics

            
              {this.state.mustKnowTopics}             
                              
           );   } }    export default App;

输出:

第三种方法:在handleClick函数。这是绑定this的更好方法,因为它避免了前两种方法中的性能问题。此外,它们在封闭范围内使用this的值,无论我们使用多少级别的嵌套,它都将引用正确的上下文。此方法使用词法this绑定,该绑定自动将它们绑定到定义它们的范围。

句法:

handleClick = () => {
// code
}

应用程序.js

import "./App.css";
import React, { Component } from "react";
  
export class App extends Component {
  constructor(props) {
    super(props);
    let styles = {
      width: "120px",
      color: "green",
      padding: "5px",
      margin: "2px",
      border: "2px solid green",
    };
    this.state = {
      mustKnowTopics: [
        
          

Searching

        
,         
          

Sorting

        
,         
          

BinarySearch

        
,         
          

SlidingWindow

        
,         
          

Stack's

        
,         
          

Queue's

        
,       ],     };   }      handleClick = () => {     let newTopics = [...this.state.mustKnowTopics];     newTopics = newTopics.slice(0, newTopics.length - 1);     this.setState({       mustKnowTopics: [...newTopics],     });   };      render() {     return (       <>         
          <>             {" "}             

Must know topics

            
              {this.state.mustKnowTopics}             
                              
           );   } }    export default App;

输出: