Javascript 如何在类组件的函数中使用React上下文
如何在类组件的函数中访问React上下文中的对象 我有以下反应成分Javascript 如何在类组件的函数中使用React上下文,javascript,reactjs,Javascript,Reactjs,如何在类组件的函数中访问React上下文中的对象 我有以下反应成分 import StoreContext from '../../context/StoreContext' class ProductForm extends Component { static contextType = StoreContext constructor(props) { super(props); } handleOptionChange(event) { cons
import StoreContext from '../../context/StoreContext'
class ProductForm extends Component {
static contextType = StoreContext
constructor(props) {
super(props);
}
handleOptionChange(event) {
const test = this.contextType.client.testObject
}
我尝试过像这样访问上下文中的客户机
对象,但它不起作用,因为它说无法读取未定义的属性
我想知道我的错误在哪里 将其更改为上下文而不是contextType
this.context.client.testObject
i、 你的代码应该是这样的
import StoreContext from '../../context/StoreContext'
class ProductForm extends Component {
static contextType = StoreContext
constructor(props) {
super(props);
}
handleOptionChange(event) {
const test = this.context.client.testObject
}
将静态属性保留为context type,并使用此属性访问方法中的context 使用要与整个应用程序共享的值定义上下文对象
const StaticBackEditor = React.createContext({isDebug: true})
在此上下文中包装整个应用程序并设置值
function App() {
return (
<Provider store={store}>
<StaticBackEditor.Provider value={{isDebug: true}}>
<div className="App">
<Layout />
</div>
</StaticBackEditor.Provider>
</Provider>
)
函数应用程序(){
返回(
)
使用组件中的值
class Tree extends React.Component<IProps, IState> {
// this must be named contextType!
static contextType = StaticBackEditor
}
// its wired that we need to access a static field through this , but you do!
{this.context.isDebug && <span className="debug">
类树扩展了React.Component{
//这必须命名为contextType!
static contextType=StaticBackEditor
}
//这是有线的,我们需要通过它访问一个静态场,但你需要!
{this.context.isDebug&&
react的哪个版本?@JjagweDennis 16.6