我试图学习反应的背景api,但我认为我对它的一些原则感到困惑。我追随的蠢事永远不会奏效。我正在使用React的正确版本。
Context.js
import React, { Component } from "react";
const MyContext = React.createContext();
export default class MyProvider extends Component {
state = {
userName: 'Kelly'
};
render() {
return(
<MyContext.Provider context={{
value: this.state.value
}}>{this.props.children}</MyContext.Provider>
);
}
}
App.jsx
import React from 'react';
import MyProvider from '../Context';
const App = () => {
return(
<MyProvider>
<MyContext.Consumer>
{context => (
<p>{context}</p>
)}
</MyContext.Consumer>
</MyProvider>
);
}
export default App;
答案 0 :(得分:1)
它确实有效,你传递上下文值的方式是不正确的。请检查以下链接 context example
const MyContext = React.createContext();
class MyProvider extends React.Component {
state = {
userName: 'Kelly'
};
render() {
return(
<MyContext.Provider value={this.state.userName}>
{this.props.children}
</MyContext.Provider>
);
}
}
class App extends React.Component {
render() {
return(
<MyProvider>
<MyContext.Consumer>
{context => (
<p>{context}</p>
)}
</MyContext.Consumer>
</MyProvider>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"))
希望这会有所帮助!!