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;输出

广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP