如何在 React 中使用钩子绑定函数? [英] How can I bind function with hooks in React?

查看:33
本文介绍了如何在 React 中使用钩子绑定函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我们在构造函数中绑定事件处理函数,或者在 React 类组件中将它们作为箭头函数,如下所示

Basically we bind event handler functions in constructor or make them as arrow functions in React class components like below

class Test extends Component{
  constructor(props){
    super(props);
    this.state = { count:0 };
    this.setCount = this.setCount.bind(this);
  }

  setCount() {
    this.setState({count: this.state.count + 1});
  }

  render() {
    return <button onClick={this.setCount}>Increase</button>
  }
}

但是在 React v16.7.0 引入钩子之后,类组件变成了具有状态的功能组件.

But after hooks are introduced in React v16.7.0 the class components became functional components with state.

那么如何将函数与函数组件中的钩子绑定?

So how can I bind the function with hooks in functional component?

推荐答案

由于函数中没有 this,因此无需在函数组件中绑定函数/回调.在类中,绑定 this 很重要,因为我们希望确保回调中的 this 引用组件的实例本身.但是,在构造函数中执行 .bind 具有另一个有用的特性,即在组件的整个生命周期中创建函数一次,并且不会在每次调用时创建新的回调render().要使用 React 钩子只初始化一次回调,您可以使用 useCallback.

There's no need to bind functions/callbacks in functional components since there's no this in functions. In classes, it was important to bind this because we want to ensure that the this in the callbacks referred to the component's instance itself. However, doing .bind in the constructor has another useful property of creating the functions once during the entire lifecycle of the component and a new callback wasn't created in every call of render(). To do only initialize the callback once using React hooks, you would use useCallback.

class Foo extends Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    console.log('Click happened');
  }

  render() {
    return <Button onClick={this.handleClick}>Click Me</Button>;
  }
}

钩子

function Foo() {
  const memoizedHandleClick = useCallback(
    () => {
      console.log('Click happened');
    },
    [], // Tells React to memoize regardless of arguments.
  );
  return <Button onClick={memoizedHandleClick}>Click Me</Button>;
}

这篇关于如何在 React 中使用钩子绑定函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆