javascript 如何在 React 中使用钩子绑定函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53215067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 10:08:20  来源:igfitidea点击:

How can I bind function with hooks in React?

javascriptreactjsreact-nativereact-hooks

提问by Hemadri Dasari

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

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

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>
  }
}

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

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

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

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

回答by Yangshun Tay

There's no need to bind functions/callbacks in functional components since there's no thisin functions. In classes, it was important to bind thisbecause we want to ensure that the thisin the callbacks referred to the component's instance itself. However, doing .bindin the constructor has another useful property of creating the functions onceduring 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.

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

Classes

班级

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>;
  }
}

Hooks

挂钩

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

回答by alecmce

You might as well write the component Fooabove like this and save yourself some typing. Note the syntax around handleClick ... it defines the closure handleClick as a field on Foo, rather than as a method. This removes the need for you to use bind to overwrite the OBject's 'handleClick' reference in the constructor. (Also, you don't need to define a constructor if you're just calling 'super'!)

您不妨像这样编写Foo上面的组件并节省一些输入。注意 handleClick 周围的语法……它将闭包 handleClick 定义为 Foo 上的一个字段,而不是一个方法。这消除了您在构造函数中使用 bind 覆盖 OBject 的“handleClick”引用的需要。(此外,如果您只是调用“超级”,则不需要定义构造函数!)

class Foo extends Component {
  handleClick = () => {
    console.log('Click happened');
  }

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

Similarly, for your original example, just declare state and setCount directly and to simplify your code:

同样,对于您的原始示例,只需直接声明 state 和 setCount 并简化您的代码:

class Test extends Component{
  state = {count: 0}

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

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