bind()是React中的內置方法,用於將數據作為參數傳遞給基於類的組件的函數。
用法:
this.function.bind(this,[arg1...]);
參數:它接受兩個參數,第一個參數是用於綁定的this關鍵字,第二個參數是參數順序那通過作為一個參數並且是可選的。
創建React應用程序:
-
步驟1:使用以下命令創建React應用程序:
npx create-react-app foldername
-
步驟2:建立專案資料夾(即資料夾名稱)之後,使用以下指令移至該資料夾:
cd foldername
範例1:
- App.js:
Javascript
import React from 'react'; class App extends React.Component { // Initialising state state = { name:'GFG', }; handler = (name) => { // Changing the state this.setState({ name:name }); }; render() { return ( <div> <h1>Name:{this.state.name}</h1> <h1>Click here to change the name</h1> {/* Passing the name as an argument to the handler() function */} <button onClick={this.handler.bind(this, 'GeeksForGeeks')}> Click Here </button> </div> ); } } export default App;
運行應用程序的步驟:從項目的根目錄中使用以下命令運行應用程序:
npm start
輸出:
範例2:我們還可以使用現代ES6提供的箭頭函數。
-
App.js:
Javascript
import React from 'react'; class App extends React.Component { // Initialising state state = { name:'GFG', }; handler = (name) => { // Changing the state this.setState({ name:name }); }; render() { return ( <div> <h1>Name:{this.state.name}</h1> <h1>Click here to change the name</h1> {/* Passing the name as an argument to the handler() function with modern ES6 feature*/} <button onClick={() => this.handler('GeeksForGeeks')}> Click Here </button> </div> ); } } export default App;
運行應用程序的步驟:從項目的根目錄中使用以下命令運行應用程序:
npm start
輸出:
相關用法
- Node.js socket.bind()用法及代碼示例
- Lodash _.bind()用法及代碼示例
- AngularJS ng-bind用法及代碼示例
- AngularJS angular.bind()用法及代碼示例
- Underscore.js _.bind()用法及代碼示例
- Google AMP amp-bind-recaptcha用法及代碼示例
- Google AMP amp-bind用法及代碼示例
- ReactJS shouldComponentUpdate()用法及代碼示例
- ReactJS componentDidMount()用法及代碼示例
- ReactJS getSnapshotBeforeUpdate()用法及代碼示例
注:本文由純淨天空篩選整理自rbbansal大神的英文原創作品 ReactJS bind() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。