25

基本上我们在构造函数中绑定事件处理函数,或者在 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>
  }
}

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

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

4

3 回答 3

65

由于没有thisin 函数,因此无需在函数组件中绑定函数/回调。在类中,绑定很重要,this因为我们希望确保this回调中的 引用组件的实例本身。但是,.bind在构造函数中执行操作还有另一个有用的属性,即在组件的整个生命周期中创建一次函数,并且不会在每次调用render(). 要使用 React 钩子只初始化一次回调,您可以使用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>;
}
于 2018-11-11T05:55:52.837 回答
4

人们来到 SO 并复制粘贴代码。把这个答案留在这里,这样 React 社区就不会错误地记住所有内容,并且可能会做不必要的工作。

功能组件

function Foo() {
  const handleClick = function(){
    // use function statements to avoid creating new instances on every render
    // when you use `bind` or arrow functions
    console.log('memoizing can lead to more work!')
  };
  return <Button onClick={handleClick}>Click Me</Button>;
}

提示:查看使用时转译的代码useCallback,看看是否有必要,然后再将其放入。如果您不确定是否需要它,则可能不需要。并确保它对您有好处,请对其进行分析。

于 2021-09-09T13:25:34.260 回答
-1

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

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

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

同样,对于您的原始示例,只需直接声明 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>
  }
}
于 2019-03-16T14:03:34.043 回答