Я реализовал React Context API и пытаюсь обновить состояние, определенное внутри провайдера, с помощью функции onClick внутри дочернего компонента.
Это то, что я делал до сих пор, в App.js У меня есть:
import { createContext } from 'react';
const MyContext = React.createContext();
export class MyProvider extends Component {
state = {
currPrj: ''
}
handleBtnClick = prjCode => {
this.setState({
currPrj: prjCode
})
}
render() {
return(
<MyContext.Provider value={{
state: this.state
}}>
{this.props.children}
</MyContext.Provider>
)
}
}
export const MyComsumer = MyContext.Consumer;
Внутри моего дочернего компонента У меня есть:
import React, { Component } from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import { MyComsumer } from "../../index";
export class ProjectCard extends Component {
constructor(props) {
super(props);
this.state = {
// currPrj: ''
};
}
render() {
return (
<MyComsumer>
{(context) => (
<div className="card card-project">
<p>{context.state.currPrj}</p>
<div className="content">
<div className="author">
<Link to={ `projects/${this.props.code}/detail/info` } onClick={() => handleBtnClick(this.props.code) }>
<h4 className="title">
{this.props.title}
</h4>
</Link>
</div>
</div>
)}
</MyComsumer>
);
}
}
export default ProjectCard;
Таким образом я получаю следующую ошибку
Failed to compile
./src/components/ProjectCard/ProjectCard.jsx
Line 32: 'handleBtnClick' is not defined no-undef
Search for the keywords to learn more about each error.
Я не понимаю, почему, потому что:
<p>{context.state.currPrj}</p>
не выдает ошибку ...
Плюс, this.props.code передано правильно в функцию?
Большое спасибо.