基本上,我们在构造函数中绑定事件处理函数,或者在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类组件成为具有状态的功能组件.

那么,我如何用函数组件中的钩子绑定函数呢?

推荐答案

没有必要在功能组件中绑定函数/回调,因为函数中没有this个.在类中,绑定this很重要,因为我们希望确保回调中的this引用组件的实例本身.然而,在构造函数中执行.bind还有另一个有用的特性,即在组件的整个生命周期中创建函数once,并且并不是每次调用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>;
}

React-native相关问答推荐

如何在Reaction Native DrawerNavigation中添加注销功能

无法解析 com.google.gms:google-services:4.3.15

React Native 应用程序没有在之前的工作代码中执行任何操作就无法运行

如何将 react-native 图像从 expo-image-picker 上传到使用 multer 的 Express.js 后端

如何在 React Navigation 5 中将父函数传递给子屏幕?

React-Native:save user preferences

使用 react-native 单击时如何更改图像和文本 colored颜色 ?

Visual Studio 2017 中的 React Native

React Native localhost 另一个调试器已经连接

通过带有对象子对象的数组react native 映射 - 与react网络中的工作方式不同?

将图标添加到drawer抽屉react-navigation v5

React Nativedropped so far性能监视器计数不断增加

创建新的 react-native 元素时出现Unexpected token import错误

如何用 Realm 元素文件组织 React Native?

Xcode 12 - 没有要编译的架构(ONLY_ACTIVE_ARCH=YES,active arch=x86_64,VALID_ARCHS=arm64e armv7s arm64 arm7)

如何在 React Native 中从底部滑入和滑出

React Context:TypeError:render is not a function

Mapping children of a parent component

xcode 使用错误的 node.js 版本

如何在 react-native 中设置 Alert 元素的样式?