我不明白为什么:
- 我有react_react-dom 16.8x
- 我的提供者和消费者之间有一个组件,以避免上述两个元素之间的循环调用。
我希望我的上下文可以在生命周期组件中直接访问,并且ReactJS提出了this.context
的方法来做到这一点。
这是我的sandbox
这是我的reactjs片段
import React, {Component}from "react";
import "./App.css";
// first we will make a new context
const MyContext = React.createContext();
// Then create a provider Component
class MyProvider extends Component {
state = {
name: 'Wes',
age: 100,
cool: true
}
render() {
return (
<MyContext.Provider value={{
state: this.state,
growAYearOlder: () => this.setState({
age: this.state.age + 1
})
}}>
{this.props.children}
</MyContext.Provider>
)
}
}
const Family = (props) => (
<div className="family">
<Person />
</div>
)
class Person extends Component {
componentDidMount(){
console.log("context: ", this.context)
}
render() {
console.log("context: ", this.context)
return (
<div className="person">
<MyContext.Consumer>
{(context) => (
<React.Fragment>
<p>Age: {context.state.age}</p>
<p>Name: {context.state.name}</p>
<button onClick={context.growAYearOlder}>🍰🍥🎂</button>
</React.Fragment>
)}
</MyContext.Consumer>
</div>
)
}
}
class App extends Component {
render() {
return (
<MyProvider>
<div>
<p>I am the app</p>
<Family />
</div>
</MyProvider>
);
}
}
export default App;
为什么this.context
为空?
任何提示都会很棒, 谢谢
最佳答案
您需要设置 contextType 来使用上下文。
关于react website无论如何,它指定了这么多。
所以唯一需要改变的是:
class Person extends Component {
componentDidMount(){
console.log("context: ", this.context)
}
render() {
console.log("context: ", this.context)
return (
<div className="person">
<MyContext.Consumer>
{(context) => (
<React.Fragment>
<p>Age: {context.state.age}</p>
<p>Name: {context.state.name}</p>
<button onClick={context.growAYearOlder}>🍰🍥🎂</button>
</React.Fragment>
)}
</MyContext.Consumer>
</div>
)
}
}
Person.contextType = MyContext;
希望这有帮助!
关于javascript - "this.context"返回一个空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54612744/