簡體   English   中英

在 class 組件 React 中使用 hook

[英]Use hook in class component React

您好,我已經檢查了有關該主題的幾篇文章,但是我沒有成功地做到這一點。 如果可能的話,我想要一個例子。

 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> ) }

沒關系

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

錯誤:無效掛鈎調用。 鈎子只能在 function 組件的內部調用。 這可能由於以下原因之一而發生:

  1. 您可能有不匹配的 React 版本和渲染器(例如 React DOM)
  2. 你可能違反了 Hooks 規則
  3. 您可能在同一個應用程序中有多個 React 副本,請參閱 fb.me/react-invalid-hook-call 以獲取有關如何調試和修復此問題的提示。

在我看來,React Hook 是一種在您不喜歡使用(反應)組件的情況下使用狀態的選項。 因此語法應該是這樣的:

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

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

我不知道這是否有效(沒時間),但也許值得一試,或者其他更有經驗的編碼員可以幫助你:)

資料來源: https://reactjs.org/docs/hooks-state.html

State管理帶一個Hook是function獨有的開發,對於class中state的任何改變都必須通過繼承function this.setState();

Function 例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM