gpt4 book ai didi

javascript - 如何获取 const MyContext = React.createContext();对于 React js 中的其他组件

转载 作者:行者123 更新时间:2023-11-29 23:25:41 25 4
gpt4 key购买 nike

我正在使用新的 Context API 制作一个新应用。在 MyProvider 组件中我得到一个错误:

undefined Provider.

那么 friend 们我该如何实现这个MyContext呢?我创建了单独的 .js 文件,我应该将 const MyContext = React.createContext(); 放在哪里?

应用程序.js

import React, {Component} from 'react';
import Calsi from './Calsi'
import MyProvider from './MyProvider'

const MyContext = React.createContext();


class App extends Component {

constructor() {
super();
window.MyContext = MyContext;
}


render() {
return (
<MyProvider>
<div>
<Calsi/>
</div>
</MyProvider>
);
}
}

export default App;

Calsi.js

import React, {Component} from 'react';
import Sum from './Sum'
export default class Calsi extends Component{
render() {
return (
<div>
<Sum/>
</div>
);
}

}

求和.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>
)
}


}

Provider.js

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>
)
}
}

我是 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={...}>

关于javascript - 如何获取 const MyContext = React.createContext();对于 React js 中的其他组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49443316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com