类组件中的 React Hook

类组件中的 react hook

介绍

在某些情况下,我们假设您必须在基于 react 类的组件中使用 react hook 概念。

但是正如你所知,如果你想在基于类的组件中直接使用它们,反应钩子只能在功能组件中工作。

它将出现错误。

那么如何做呢,有一个解决方案。

有3步解决方案

  1. 创建自定义hook,(你可以直接使用hook,但不会获得更多好处)
  2. 在高阶组件中使用钩子
  3. 我们需要将高阶组件包装在基于类的组件中。

创建自定义 hook

import {usestate} from 'react';

const usegreet = () => {
  const [text, settext] = usestate('');

//... do any additional operation / hooks you want to add

return text;   
}

创建高阶组件

// import usegreet

export const myhigherordercomponentdemo = (component) => {

  return (props) => {
    const text = usegreet();

    return <component text="{text}"></component>;
  }
}

将高阶组件包装在基于类的组件中

// import useGreet

class MyClass extends React.component {

render() {
   return (
    <p>{this.props.text}</p>
  )
}

}

export default MyHigherOrderComponentDemo(MyClass);

以上就是类组件中的 React Hook的详细内容,更多请关注www.sxiaw.com其它相关文章!