[英]How to pass function from FUNCTIONAL to CLASS component and access it outside of render( without prop ), using context in react js?
[英]Pass prop from Consumer -> Provider context and access it outside of Provider render?
我有一個名為“主頁”的組件,它是我網站的主頁。 這個 Home 組件使用名為“ProductContext”的上下文來訪問 data.js 文件中的所有產品。 問題是,我的網站的每個頁面都將有多個 *data.js 文件,所以我去告訴上下文文件“我在”哪個頁面,以便它訪問相應的 *data.js 文件。
“家”組件:
class Home extends Component {
state = {
page: "Home",
};
componentDidMount() {}
render() {
return (
<React.Fragment>
<div className="py-2">
<div className="container-fluid">
<Title title="PRODUCTS" className="pl-5" />
<div
className="row no-gutters "
style={{ justifyContent: "center" }}
>
<ProductConsumer page={"Home"}>
{(value) => {
console.log(value);
return value.products.map((product) => {
return <Product key={product.id} product={product} />;
});
}}
</ProductConsumer>
</div>
</div>
</div>
</React.Fragment>
);
}
}
export default Home;
產品上下文:
render() {
return (
<ProductContext.Provider
value={{
...this.state,
handleDetail: this.handleDetail,
addToCart: this.addToCart,
openModal: this.openModal,
closeModal: this.closeModal,
increment: this.increment,
decrement: this.decrement,
removeItem: this.removeItem,
clearCart: this.clearCart,
setPage: this.setPage,
}}
>
{this.props.children}
</ProductContext.Provider>
);
}
}
你可以看出我嘗試了一些方法,比如在上下文中通過道具或 function 傳遞它。 我確定我很接近,但我不知道該怎么做。 我見過其他示例,其中您調用 Provider function,最常見的是“onClick”,但這需要在構建或安裝 Home 組件或 ProductContext 時發生,以便 Page 組件可以提取正確的數據。 我的意思是說:
//In Home Component
componentDidMount() {
let context = this.context;
context.setPage("Home");
}
當然,這不起作用。
我對上下文如何工作的理解非常有限。 從這次經歷中,我想我了解到上下文應該被視為提供數據的東西,而不是獲取數據的東西。
我解決了這個問題,首先將上下文中的數據排序到不同的 arrays 中,然后將相應的數組傳遞給每個頁面。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.