我正在尝试从App.js的子组件中导入创建的上下文。
App.js
export const FilterContext = React.createContext("test");
export default class App extends React.Component {
render() {
return (
<div className="App">
<Navigation />
<Hero />
<FilterContext.Provider value="hello">
<OfferSorting />
<div className="wrapper">
<div className="container">
<Offer />
</div>
</div>
<NewOfferButton />
</FilterContext.Provider>
</div>
);
}
}
然后我要在<OfferSorting />
中访问我的上下文
OfferSorting.js
import { FilterContext } from "../../../App";
export default class OfferSorting extends React.Component {
static contextType = FilterContext;
constructor(props) {
super(props);
}
componentDidMount() {
console.log(this.context)
}
}
但是在OfferSorting.js
中,它将引发错误Cannot access 'FilterContext' before initialization
。如何访问上下文,而不使用道具?