如何在 React 经典 `class` 组件中使用 React 钩子? [英] How can I use React hooks in React classic `class` component?

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

问题描述

在这个例子中,我有这个反应类:

class MyDiv 扩展 React.component构造函数(){this.state={sampleState:'hello world'}}使成为(){返回 

{this.state.sampleState}}}

问题是我是否可以为此添加 React 钩子.我知道 React-Hooks 是 React Class 风格的替代品.但是如果我想慢慢迁移到 React hooks 中,我可以在 Classes 中添加有用的 hooks 吗?

解决方案

高阶组件 是在 hooks 出现之前我们一直在做这种事情的方式.您可以为钩子编写一个简单的高阶组件包装器.

function withMyHook(Component) {返回函数 WrappedComponent(props) {const myHookValue = useMyHook();return <Component {...props} myHookValue={myHookValue}/>;}}

虽然这并不是真正直接从类组件中使用钩子,但这至少允许您使用来自类组件的钩子的逻辑,而无需重构.

class MyComponent 扩展 React.Component {使成为(){const myHookValue = this.props.myHookValue;返回 <div>{myHookValue}</div>;}}导出默认 withMyHook(MyComponent);

In this example, I have this react class:

class MyDiv extends React.component
   constructor(){
      this.state={sampleState:'hello world'}
   }
   render(){
      return <div>{this.state.sampleState}
   }
}

The question is if I can add React hooks to this. I understand that React-Hooks is alternative to React Class style. But if I wish to slowly migrate into React hooks, can I add useful hooks into Classes?

解决方案

High order components are how we have been doing this type of thing until hooks came along. You can write a simple high order component wrapper for your hook.

function withMyHook(Component) {
  return function WrappedComponent(props) {
    const myHookValue = useMyHook();
    return <Component {...props} myHookValue={myHookValue} />;
  }
}

While this isn't truly using a hook directly from a class component, this will at least allow you to use the logic of your hook from a class component, without refactoring.

class MyComponent extends React.Component {
  render(){
    const myHookValue = this.props.myHookValue;
    return <div>{myHookValue}</div>;
  }
}

export default withMyHook(MyComponent);

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

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