值未在react中使用上下文传递给子组件

时间:2020-05-22 03:31:05

标签: reactjs react-context

雇员ID不会反映在“雇员”组件中。

const employeecontext= React.createContext();

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      id: 101
    };
  }
  render() {
    return (
      <div>
        <h1>welcome to App</h1>
        <p>
          <label> Employee id: {this.state.id}</label>
        </p>
        <employeecontext.Provider value={this.state}>
          <Employee />
        </employeecontext.Provider>
      </div>
    );
  }
}

员工类别:

class Employee extends React.Component {
  static context = employeecontext;

  render() {
    return (
      <div>
        <h1>welcome to employee</h1>
        <p>
          <label> Employee id: {this.context.id}</label>
        </p>
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:1)

问题就在这一行:

static context = employeecontext;

只需使用正确的静态类属性contextType

像这样:

static contextType = employeecontext;