Javascript 访问类组件中使用useContext创建的上下文
我问了一个问题,如何将函数从React公开到外部HTML: 因为我找不到一个纯函数式的解决方案,所以我在类中尝试了它,因为在类中有“this”,我可以绑定到窗口Javascript 访问类组件中使用useContext创建的上下文,javascript,reactjs,Javascript,Reactjs,我问了一个问题,如何将函数从React公开到外部HTML: 因为我找不到一个纯函数式的解决方案,所以我在类中尝试了它,因为在类中有“this”,我可以绑定到窗口 import React from 'react'; import MyContext from '../context/Context'; class Api extends React.Component{ static contexType = MyContext; constructor(){
import React from 'react';
import MyContext from '../context/Context';
class Api extends React.Component{
static contexType = MyContext;
constructor(){
super();
window.api = this;
}
exposed(value){
let c = this.context;
console.log("value", value)
console.log(c.number);
//c.setNumber({...number, "n1": value})
}
render(){
return(null);
}
}
export default Api;
在CMS模板中,我定义了这个输入字段:
<input type="number" onchange="window.api.exposed(this.value)" />
Api组件get插入到App.js中,如下所示:
function App() {
return (
<ContextProvider>
<Api />
</ContextProvider>
);
}
并将其置于上下文中:
return(
<MyContext.Provider value={{
number
}}>
<div className="contextProvider">
{props.children}
</div>
</MyContextContext.Provider>
);
返回(
{props.children}
);
为什么我不能从类组件访问上下文
static contexType = MyContext;
缺少一个“t”
static contextType = MyContext;
您能否分享一个示例,说明如何尝试从类组件访问上下文?现在,您只演示了如何提供上下文,而不是使用上下文。不,这是一个愚蠢的打字错误
static contexType = MyContext;
static contextType = MyContext;