簡體   English   中英

我可以將 class 基礎組件放入 function 基礎組件中以使用反應掛鈎嗎?

[英]Can I put class base components inside function base components to use react hooks?

我有一個主要使用 class 基本反應組件編寫的應用程序,但是我們正在使用 Stripe 實現付費專區功能。

問題是條紋使用鈎子,它不適用於 class 基本組件。 是否可以將子 class 基本組件放入父 function 基本組件中以實現此目的。 在不將每個組件重寫為 function 基本組件的情況下,我將如何 go 做到這一點。

每次嘗試將 function 基本組件與 class 基本子組件包含在一起總是會產生此錯誤:

錯誤:無效的掛鈎調用。 鈎子只能在 function 組件的主體內部調用。

是否有任何解決方法,或者我應該將所有組件重新編寫為功能組件?

一個使用 react-router-dom 查詢參數的快速示例,然后將這些參數傳遞到 class 基礎子組件。

 function useQuery() {
   return new URLSearchParams(useLocation().search);
 }

const App = () => {
let query = useQuery();

return (
  <Provider store={store}>
    <Router>
      <div className="App">
        <Navbar />
        <Switch>
          {/* Public Pages */}
          <Route exact path="/" component={Landing} ref={query.get('ref')} /> 
       </Switch>
      </div>
    </Router>
  </Provider>
)
}
 export default App;

然后假設着陸組件是一個簡單的 class 基礎組件,它將把 prop 設置到 state 中。

組件的類型與父子關系無關。 但是你不能在 classBased 組件中使用鈎子。 僅在功能性

這是功能組件作為父級和 Class 作為子級的代碼示例

import React , {Component}from "react";
import "./styles.css";

const App = () => {
  return (
    <div className="App">
      <h1>I Am Parent Functional Component</h1>
      <Child />
    </div>
  );
};

export default App;

class Child extends Component
{

  render(){
    return(
      <h2>I am Class Child Component</h2>
    )
  }
}

好的,我發現了這個問題的問題。 由於我在互聯網上發現同樣的問題沒有得到解答,所以我決定自己回答這個問題,僅供任何尋求我遇到的相同解決方案的人將來參考。

您可以在父 Function 基礎組件上使用 Hook,並將信息傳遞到子基礎組件中。

渲染應用程序時,出現錯誤

Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

但是,此錯誤是由於 npm 中的過時模塊造成的。 我剛剛將 react-router-dom 從 4.1 更新到 5.2.0 npm update react-router-dom似乎解決了使用功能基礎組件作為父級的問題。

更新模塊后,我能夠在父 function 基本組件中使用掛鈎,並使用道具將其傳遞給子 class 基本組件。

暫無
暫無

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

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