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

查看:40
本文介绍了如何在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天全站免登陆