如何从react中的类组件访问上下文变量?

问题描述

我需要使用类组件(称为“ Frage”)从我的React-Context中调用名为“ chatbotContext”的变量“ value”。

但是,当我使用useContext时,我收到一条错误消息,指出只允许在React函数中使用Hooks。

如何访问类组件“ Frage”中的上下文变量?

这是我(显然)从上下文访问值的错误尝试

import chatbotContext from "../../Context/chatbot/chatbotContext";

const chatbotContext = useContext(chatbotContext);
const { value } = chatbotContext;
console.log(value);

class Frage extends Rete.Component {
  constructor() {
    super("Frage");
  }

  // Build node elements
  builder(node) {
    // new input
    var inp = new Rete.Input("input1","Input",numSocket,true);
    // new output1
    var out1 = new Rete.Output("output1","Correct",false);
    // new output2
    var out2 = new Rete.Output("output2","Incorrect",false);
    // new control1
    var ctrl1 = new MyControl(
      this.editor,node,"chatbottext","Welches ist der höchste Berg der Welt?"
    );

解决方法

Frage是一个类组件,您正在尝试使用只能在功能组件中使用的useContext。就您而言,您可以使用如下上下文:

import React,{ Component } from 'react'
import UserContext from './UserContext'

class HomePage extends Component {
  static contextType = UserContext

  componentDidMount() {
    const user = this.context

    console.log(user) // { name: 'Sagar',loggedIn: true }
  }

  render() {
    return <div>{user.name}</div>
  }
}

希望这个答案会有所帮助。谢谢