ReactJS – bind() 方法


在本文中,我們將瞭解如何向 React 應用程式中的函式傳遞引數。

React 有一個預定義的 bind() 方法,我們可以使用它來將引數傳遞給基於類的元件中的函式。

語法

this.func.bind(this,[args...])

它接受兩個引數,this 關鍵字和 arguments。'this' 關鍵字用於將引用傳遞給該函式,而第二個引數作為引數傳遞給函式。

示例

在此示例中,我們將構建一個 React 應用程式,當點選按鈕時,它會將引數傳遞給函式。

App.jsx

import React from 'react';

class App extends React.Component {
   constructor(){
      super();
      this.state = {
         name: 'Rahul Bansal',
         email: null,
      };
   }

   fetch = (email) => {
      this.setState({ email: email });
   };
   render() {
      return (
         <div>
            <h1>Name: {this.state.name}</h1>
            <h1>{this.state.email ? 'Email: ${this.state.email}' : null}</h1>
            <button onClick={this.fetch.bind(this, 'qwerty@gmail.com')}>
               Fetch Email
            </button>
         </div>
      );
   }
}
export default App;

輸出

更新日期:18-Mar-2021

5K+ 次瀏覽

開始你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.