![](/img/trans.png)
[英]How to use useNavigate( ) React-Router-Dom Hook in Class Component
[英]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 組件的內部調用。 這可能由於以下原因之一而發生:
在我看來,React Hook 是一種在您不喜歡使用(反應)組件的情況下使用狀態的選項。 因此語法應該是這樣的:
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
const [ref, inView, entry]: useInView({
/* Optional options */
threshold: 0,
})
};
}
render() {
return (
<>
</>
);
}
}
我不知道這是否有效(沒時間),但也許值得一試,或者其他更有經驗的編碼員可以幫助你:)
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.