Javascript 如何获取常量MyContext=React.createContext();对于React js中的其他组件
我正在使用新的上下文API制作一个新的应用程序。在Javascript 如何获取常量MyContext=React.createContext();对于React js中的其他组件,javascript,reactjs,Javascript,Reactjs,我正在使用新的上下文API制作一个新的应用程序。在MyProvider组件中,我得到一个错误: 未定义的提供程序 那么,朋友们,我如何才能做到这一点呢?我创建了单独的.js文件,我应该将const MyContext=React.createContext()放在哪里 App.js import React,{Component}来自'React'; 从“/Calsi”导入Calsi 从“./MyProvider”导入MyProvider const MyContext=React.create
MyProvider
组件中,我得到一个错误:
未定义的提供程序
那么,朋友们,我如何才能做到这一点呢?我创建了单独的.js
文件,我应该将const MyContext=React.createContext()放在哪里代码>
App.js
import React,{Component}来自'React';
从“/Calsi”导入Calsi
从“./MyProvider”导入MyProvider
const MyContext=React.createContext();
类应用程序扩展组件{
构造函数(){
超级();
window.MyContext=MyContext;
}
render(){
返回(
);
}
}
导出默认应用程序;
Calsi.js
import React,{Component}来自'React';
从“./Sum”导入Sum
导出默认类Calsi扩展组件{
render(){
返回(
);
}
}
Sum.js
import React,{Component}来自'React';
const MyContext=window.MyContext;
导出默认类和扩展组件{
render(){
返回(
{(上下文)=>(
a:{context.state.a}
b:{context.state.b}
求和:{context.state.a+context.state.b}
增量a
)}
)
}
}
Provider.js
import React,{Component}来自'React';
const MyContext=window.MyContext;
导出默认类MyProvider扩展组件{
状态={
答:0,,
b:20,
}
render(){
返回(
这是我的国家({
a:这个州,a+1
})
}}>
{this.props.children}
)
}
}
我是react的新手,所以我如何才能正确地做到这一点?此外,我使用的是react 16.3.0 alpha2版本。谢谢您的帮助。您必须导出您的上下文。不要将其附加到浏览器的窗口对象(window.MyContext=MyContext
)
创建一个新文件并将其命名为MyContext.js
export const MyContext = React.createContext();
然后将其导入您的Provider.js
:
import { MyContext } from "./MyContext";
...
<MyContext.Provider value={...}>
从“/MyContext”导入{MyContext};
...
为什么不试着把它放在index.js中呢!
import React, {Component} from 'react';
const MyContext = window.MyContext;
export default class Sum extends Component {
render() {
return (
<div>
<MyContext.Consumer>
{(context) => (
<React.Fragment>
<p>a:{context.state.a}</p>
<p>b:{context.state.b}</p>
<p>Sum: {context.state.a + context.state.b}</p>
<button onClick={context.increaseA}>increment a</button>
</React.Fragment>
)}
</MyContext.Consumer>
</div>
)
}
}
import React, {Component} from 'react';
const MyContext = window.MyContext;
export default class MyProvider extends Component {
state = {
a: 0,
b: 20,
}
render() {
return (
<MyContext.Provider value={{
state: this.state,
increaseA: () => this.setState({
a: this.state.a + 1
})
}}>
{this.props.children}
</MyContext.Provider>
)
}
}
export const MyContext = React.createContext();
import { MyContext } from "./MyContext";
...
<MyContext.Provider value={...}>