雇员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>
);
}
}
答案 0 :(得分:1)
问题就在这一行:
static context = employeecontext;
只需使用正确的静态类属性contextType
。
像这样:
static contextType = employeecontext;