簡體   English   中英

ReactJS 函數式組件“this”關鍵字問題

[英]ReactJS Functional Component “this” keyword problem

我搜索了類似的問題,但沒有一個能解決我的疑問。 在這種情況下,如何將“this”更改為反應功能組件: <SimpleStorage parent={this}/>其中此組件屬於一個庫(稱為 react-simple-storage)並寫入功能組件中。 我看到的所有例子都是指this.statethis.objectthis.function但沒有一個是關於this

const Books = () => { 
...  
return <Router>  
            <SimpleStorage parent={this}/> 
            <Routes/>
       </Router>

當我嘗試以這種方式運行時,他運行但控制台拋出:

No "parent" prop was provided to react-simple-storage. A parent component's context is required in order to access and update the parent component's state.
            
Try the following: <SimpleStorage parent={this} />

如何設置功能組件的組件狀態? 我必須在父組件中實例化一個變量嗎? 有什么可以做的嗎?

該庫旨在與類組件一起使用,因此最好使用該類型的組件。

但是,如果您查看 lib 的源代碼,您會發現parent使用了兩個 props: statesetState ,因此您可以創建一個狀態容器來保存所有函數組件的狀態:

const [state, setState] = useState(initState);

然后將其傳遞給:

<SimpleStorage parent={{state, setState}} />

暫無
暫無

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

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