简体   繁体   中英

Use hook in class component React

Hello I have checked the few articles on the subject, but I was not successful in doing the same. I would like if possible an example if possible.

 import React from 'react' import { useInView } from 'react-intersection-observer' const Component = () => { const [ref, inView, entry] = useInView({ /* Optional options */ threshold: 0, }) return ( <div ref={ref}> <h2>{`Header inside viewport ${inView}.`}</h2> </div> ) }

it's ok

 class Nameclasse extends Component { constructor(props) { super(props); const [ref, inView, entry] = useInView({ /* Optional options */ threshold: 0, }) } render() { return (<div></div>); } }

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app See fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.

In my opinion React Hook is a option to use states in situations where you won`t like to use (react) components. Therefore the syntax should look like a this:

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      const [ref, inView, entry]: useInView({
         /* Optional options */
         threshold: 0,
      })
    };
  }

  render() {
    return (
      <>
      </>
    );
  }
}

I don`t if this is working (no time), but maybe its worth a try or some other more experienced coder could help you:)

source: https://reactjs.org/docs/hooks-state.html

State management with a Hook is exclusive to development by function, for any change of a state in a class you must go through the inherited function this.setState();

Function ex:

function Counter() {
    const [count,setCount] = useInView(0)
    return (<div> <button onclick={() => {setCount(count + 1)}}>Click me + 1</button> {count}</div>);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM